Sorting integer value in php [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I have 19 variables in a php file.
$a = 20;
$b = 23;
$c = 2;
$d = 92;
$e = 51;
$f = 27;
$g = 20;
$h = 20;
.....
.....
$s = 32;
What i need, I need to show only top 5 value. And there is similar value for some variables. In that case, I need to show the first value only if it is in the top 5 value.
I am not having any clue on doing this.
After receiving some feedback given bellow, i have used array and asort
Here is the example-
<?php
$fruits = array("a" => "32", "b" => "12", "c" => "19", "d" => "18");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
The output looks like this:
b = 12 d = 18 c = 19 a = 32
I need the reverse result. Meaning, 32, 19, 18, 12.....
Any help. Just dont know the exact command

This is best done by putting the values of the variables into an array and running
sort($arr); (this is from lowes to highest).
rsort($arr); sorts high to low.
http://php.net/manual/en/array.sorting.php
Then you can get the first values at array-index 0,1,2,3 and 4 which will be the biggest numbers.
So:
$arr= array ($a,$b,$c, ....);
rsort($arr);
var_dump($arr); // gives the output.
$arr[0] // biggest number
$arr[4] // 5th biggest number.

A funny way to do this:
$a = 20;
$b = 23;
$c = 2;
$d = 92;
$e = 51;
$f = 27;
$g = 20;
$h = 20;
$array = compact(range('a', 'h'));
rsort($array);
foreach(array_slice($array, 0, 5) as $top) {
echo $top, "\n";
}
Output
92
51
27
23
20
Demo: http://3v4l.org/Wi8q7

Do they need to be individual variables? Storing the values in an array is a better option. So, either manually put all the variables into an array, or change your structure to something more like:
$arr = array(
'a' = 20,
'b' = 23,
'c' = 2,
'd' = 92,
'e' = 51,
....
....
's' => 32
);
or similar. Then use sort() to sort the array:
sort($arr);
To get the top 5, use array_slice():
$arr = array_slice($arr, 0, 5);
See demo
Note: sort() may not be best option for you depending on the desired result. For other sorting options, consult the manual: http://php.net/manual/en/array.sorting.php

<?php
array_push($data,$a);
array_push($data,$b);
.
.
.
$sorted_array = usort($data, 'mysort');
$top5 = array_splice($sorted_array,5);
if(in_array($your_variable,$top5)){
return $top5[0];
}else {
return $top5;
}
function mysort($a,$b){
if ($a == $b) {
return 0;
}
return ($a < $b) ? 1 : -1;
}
?>

$array=array();
for ($i=97;$i<=115;$i++){ //decimal char codes for a-s
$var =chr($i);
$array[]= $$var; //variable variable $a- $s
}
asort($array);
var_dump($array);

Related

Change the sorting of every 5 array of number from ascending to descending and vice versa without using php built in function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have an array number below,
$arr = [2,5,1,12,-5,4,-1,3,-3,20,8,7,-2,6,9]
The expected output must be:
-5,-3,-2,-1,1,20,12,9,8,7,2,3,4,5,6
The sorting must be change every 5 array of number from ascending to descending and vice versa. So, if the first 5 digits is sorted as ascending, the second 5 digits must be sorted as descending and so on.
But I got:
-5,-3,-2,-1,1,2,3,4,5,6,7,8,9,12,20
Below my code:
$arr = array(2,5,1,12,-5,4,-1,3,-3,20,8,7,-2,6,9);
function arr_sort($array) {
// get the size of array
$countArr = count($array);
for ($i=0; $i<$countArr; $i++) {
for ($j=$i; $j<$countArr; $j++) {
if ($array[$i] > $array[$j]) {
$temporary = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $temporary;
}
}
}
// order ascending and descending
$array = implode(',', $array);
return $array;
}
print_r(arr_sort($arr));
Using PHP built-in functions definitely help:
/**
* #param int[] $numbers
* #return int[]
*/
function arr_sort(array $numbers): array
{
// Sort items in ascending order first
sort($numbers, SORT_NUMERIC);
$result = [];
$fetch_lowest = true;
// Process until the input array is empty
while (count($numbers) !== 0) {
if ($fetch_lowest) {
// Extract the 5 lowest numbers and keep them into ascending order
$extract = array_splice($numbers, 0, 5);
} else {
// Extract the 5 highest numbers and reverse items to descending order
$extract = array_splice($numbers, -5, 5);
$extract = array_reverse($extract);
}
// Save the extracted items and switch the highest/lowest flag
$result = array_merge($result, $extract);
$fetch_lowest = !$fetch_lowest;
}
return $result;
}
$input = [2,5,1,12,-5,4,-1,3,-3,20,8,7,-2,6,9];
$sorted = arr_sort($input);
var_dump(implode(',', $sorted));
string(35) "-5,-3,-2,-1,1,20,12,9,8,7,2,3,4,5,6"
I think this is what you are going for. We chunk the array into groups of 5, then take a grouping one at a time, first from the front, then the back, repeating that pattern. If we take from the back, we then also need to sort it in reverse.
$arr = [2,5,1,12,-5,4,-1,3,-3,20,8,7,-2,6,9];
$a = $arr;
asort($a);
$a = array_chunk($a, 5);
$output = [];
$idx = 0;
while($a){
if($idx++ % 2){
$b = array_pop($a);
arsort($b);
}else{
$b = array_shift($a);
}
$output = array_merge($output, $b);
}
var_dump($output);
Demo here: https://3v4l.org/KGgWI

Get the name of the variable which has the second lowest/smallest value with PHP

I have 4 variables and each of those have an integer assigned to them. Could anybody please let me know how I can get the name of the variable which has the second smallest value?
Thanks.
Use compact to set the variables to one array, sort the array, then use array slice to get the second value.
Then optionally echo the key of the second value.
$a = 2;
$b = 7;
$c = 6;
$d = 1;
$arr = compact('a', 'b', 'c', 'd');
asort($arr);
$second = array_slice($arr,1,1);
Echo "variable name " . Key($second) ."\n";
Echo "value " . ${key($second)};
https://3v4l.org/SVdCq
Updated the code with how to access the original variable from the array
Unless you have a structured way of naming your variables eg prefix_x there is no real way.
Recommended way is using an array like this:
$array = array(
"a" => 3,
"b" => 2,
"c" => 1,
"d" => 6
);
// Sort the array descending but keep the keys.
// http://php.net/manual/en/function.asort.php.
asort($array);
// Fetch the keys and get the second item (index 1).
// This is the key you are looking for per your question.
$second_key = array_keys($array)[1];
// Dumping the result to show it's the second lowest value.
var_dump($array[$second_key]); // int(2).
To be more in line with your question you can create your array like this.
$array = array();
$array['variable_one'] = $variable_one;
$array['some_random_var'] = $some_random_var;
$array['foo'] = $foo;
$array['bar']= $bar;
// Same code as above here.
Instead of using 4 variables for 4 integer values, you can use an array to store these values. Sort the array and print the second index of the array i.e. 1.
<?php
$x = array(2,3,1,6);
$i = 0, $j = 0, $temp = 0;
for($i = 0; $i < 4; $i++){
for($j=0; $j < 4 - $i; j++){
if($x[$j] > $x[$j+1]){
$temp = $x[$j];
$x[$j] = $x[$j+1];
$x[$j+1] = $temp;
}
}
}
for($j = 0; $j < 4; $j++){
echo $x[$j];
}
echo $x[1];
?>
First you need to have all Variables in an Array. You can do this this way:
$array = array(
'a' => 3,
'b' => 6,
'c' => 2,
'd' => 1
);
or this way:
$array['a'] = 3;
$array['b'] = 6;
// etc
Then you need to sort the Items with natsort() to receive a natural Sorting.
natsort($array);
Then you flip the Array-Keys with the Values (In Case you want the Value, skip this Line)
$array = array_flip($array);
After this you jump to the next Item in the Array (Position 1) by using next();
echo next($array);
Makes in Total a pretty short Script:
$array = array(
'a' => 3,
'b' => 6,
'c' => 2,
'd' => 1
);
natsort($array);
$array = array_flip($array);
echo next($array);

PHP letter value in For Loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am having problems with my PHP code, I am trying to display a string with a value. For example, A = 1, B = 2. So if I had a string value of Cat, it would display a value of 3120 and also would add all the values together.
Many Thanks,
Jonathan
You can use ord() to get ASCII value and subtract 96. Example:
$str = 'cat';
$val = strtolower($str);
for($i = 0; $i < strlen($str); $i++){
echo ord($val[$i]) - 96;
}
strtolower() to convert lower case latter.
Create an associative array. Keys should be the letters, and values should store the values.
Get the letters, and get the value, and concat them into a new string:
$string = 'Cab';
$lettersArray = array(
'a' => 1,
'b' => 2,
'c' => 3,
//and so on
);
$valueString = '';
for ($i=0; $i < strlen($string); $i++) {
$letter = strtolower(substr($string,$i,1));
$valueString .= $lettersArray[$letter];
}
echo $valueString;
Output is:
312
Organize letter and value in a array
$letters = array(
'a' => 1
, 'b' => 2
, ...
);
loop the string
$string = "cat";
$sum = 0;
for($i = 0; i<strlen($string);$i++) {
$index = $string[$i];
$sum += $letters[$index];
print $letters[$index];
}
finally, print the sum
print $sum;

PHP Script and max() Value

Sorry for my bad English and thanks for your help in advance! I have kind of a tricky problem I've encountered while coding. Here's the point:
I need a script that essentially extracts the 5 max values of 5 arrays, that are "mixed", i.e. they contain "recurrent" values. Here is an example:
array1(a, b)
array2(a, c, d, e, g)
array3(b, d, g, h)
array4(e, t, z)
array5(b, c, d, k)
The 2 essential requests are:
1) the sum of those 5 arrays (array1+array2+array3...) MUST be the highest possible...
2) ...without repeat ANY value previously used** (e.g. if in array1 the top value was "b", this cannot be re-used as max value in arrays 3 or 5).
Currently I have this...:
$group1 = array(a, b);
$group = array(a, b, c, d);
$max1a = max(group1);
$max2a = max(group2) unset($max1a);
$sum1 = $max1a + $max2a;
$max2b = max(group2);
$max1b = max(group1)
unset($max2b);
$sum2 = $max1b + $max2b;
if($sum1 > $sum2) {
echo $sum1
} else {
echo $sum2
}
... but it's kinda impossible to use this code with 5 arrays, because I should compare 5! (120...!!!) combinations in order to find the max sum value.
I know the problem is quite difficult to explain and to solve, but I really need your help and I hope you can save me!!!
Cheers
I'm adding this as another answer to leave the previous one intact for someone coming across this looking for that variation on this behaviour.
Given the 2 arrays:
$array1 = array(30, 29, 20);
$array2 = array(30, 20, 10);
The maximum sum using one element from each is 59 - this is dramatically different to my previous approach (and the answers' of others) which took the max element of the first array and then the highest element of the next array that is not equal to any previously used value - this would give 50 instead.
The code you want is this:
$mainArray = array();
$mainArray[] = array(30, 29, 20);
$mainArray[] = array(30, 20, 10);
$tempArray = array();
$newArray = array();
foreach($mainArray as $innerArray) {
$newArray = array();
if (count($tempArray) == 0) {
foreach ($innerArray as $value) {
$newArray[] = array('total' => $value, 'used' => array($value));
}
}
else {
foreach ($tempArray as $key => $innerTempArray) {
$placed = FALSE;
foreach ($innerArray as $value) {
if (!(in_array($value, $innerTempArray['used']))) {
$newArray[] = array('total' => $tempArray[$key]['total'] + $value, 'used' => $tempArray[$key]['used']);
$newArray[count($newArray) - 1]['used'][] = $value;
$placed = TRUE;
}
}
if (!($placed)) {
echo "An array had no elements that had not already been used";
die();
}
}
}
$tempArray = $newArray;
}
$total = 0;
if (count($newArray) == 0) {
echo "No data passed";
die();
}
else {
$total = $newArray[0]['total'];
}
for ($i = 0; $i < count($newArray); $i++) {
if ($newArray[$i]['total'] > $total) {
$total = $newArray[$i]['total'];
}
}
var_dump($total);
EDIT - Do not repeat used variables (but repeated values are ok):
Let
//$a = 30, $b = 30, $c = 25, $d = 20, $e = 19
$array1 = array($a, $c, $d);
$array2 = array($b, $d, $e);
We want to choose $a from $array1 and $b from $array2 as these give the largest sum - although they're values are the same that is allowed because we only care if the names of the variables saved to that place are the same.
With the arrays in the above format there is no way of achieving the desired behaviour - the arrays do not know what the name of the variable who's value was assigned to their elements, only it's value. Therefore we must change the first part of the original answer to:
$mainArray[] = array('a', 'c', 'd');
$mainArray[] = array('b', 'd', 'e');
and also have either the of the following before the first foreach loop (to declare $a, $b, $c, $d, $e)
//either
extract(array(
'a' => 30,
'b' => 30,
'c' => 25,
'd' => 20,
'e' => 19
));
//or
$a = 30; $b = 30; $c = 25; $d = 20; $e = 19;
The above both do exactly the same thing, I just prefer the first for neatness.
Then replace the line below
$newArray[] = array('total' => $value, 'used' => array($value));
with
$newArray[] = array('total' => ${$value}, 'used' => array($value));
The change is curly brackets around the first $value because that is then evaluated to get the variable name to use (like below example):
$test = 'hello';
$var = 'test';
echo ${$var}; //prints 'hello'
A similar change replaces
$newArray[] = array('total' => $tempArray[$key]['total'] + $value, 'used' => $tempArray[$key]['used']);
with
$newArray[] = array('total' => $tempArray[$key]['total'] + ${$value}, 'used' => $tempArray[$key]['used']);
Now the code will function as wanted :)
If you are dynamically building the arrays you are comparing and can't build the array of strings instead of variables then there is no way to do it. You would need some way of extracting "$a" or "a" from $a = 30, which PHP is not meant to do (there are hacks but they are complicated and only work in certain situations (google "get variable name as string in php" to see what I mean)
If by the top value you mean the first alphabetically then the following would work:
$array1 = array('a', 'b');
$array2 = array('a', 'c', 'd', 'e', 'g');
$array3 = array('b', 'd', 'g', 'h');
$array4 = array('e', 't', 'z');
$array5 = array('b', 'c', 'd', 'k');
$mainArray = array($array1, $array2, $array3, $array4, $array5);
foreach ($mainArray as $key => $value) {
sort($mainArray[$key]);
}
$resultArray = array();
foreach($maniArray as $key1 => $value1) {
$placed = FALSE;
foreach ($value1 as $value2) {
if (!(in_array($value2, $resultArray))) {
$resultArray[] = $value2;
$placed = TRUE;
break;
}
}
if (!($placed)) {
echo "All the values in the " . ($key + 1) . "th array are already max values in other arrays";
die();
}
}
var_dump($resultArray);
I'm not sure, of i really understood your problem correctly, these are my assumptions:
You have five arrays containing numbers
These numbers can occur multiple times across the arrays
You want to find the highest possible sum of elements across your arrays
The sum uses one single value of each array
But the sum must not use the same number twice
Is that correct?
If Yes, then:
The highest possible sum across all arrays is always the sum of the largest elements. If you do not want to use the same number twice, you can just get the maximum from the first array, remove it from all the others and then sum up all the remaining maxima.
Like so:
$arrays = array();
$arrays[] = array(1, 2);
$arrays[] = array(1, 3, 4, 5, 7);
$arrays[] = array(2, 4, 7, 8);
$arrays[] = array(5, 20, 26);
$arrays[] = array(2, 3, 4, 11);
for($i=0, $n=count($arrays); $i<$n; $i++) {
if($i===0) {
$a1max = max($arrays[$i]);
$sum = $a1max;
} else {
$duplicate_pos = array_search($a1max, $arrays[$i]);
if($duplicate_pos !== FALSE) {
unset($arrays[$i][$duplicate_pos]);
}
$sum += max($arrays[$i]);
}
}
echo "sum: " . $sum . "\n";
Assuming you have grouped together all your values in one array like this,
$array = array(
array(1,2,3),
array(1,2,3,4),
array(1,2,3,4,5,6),
array(1,2,3,4,5,6),
array(1,2,3,4,5,6,7)
);
Loop through $array, and get the highest value which has not been used previously,
$max = array();
foreach($array as $value)
$max[] = max(array_diff($value, $max));
Calculate the sum of all values with array_sum(),
echo "The maximal sum is: ".array_sum($max);

How to make an array of elements which not in range of another array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
There is an array of numbers from 0 to 10000
$a = array();
$a = range(0,10000);
I have some values which are dynamic coming from database are in array like
$b = array("100-200","400-500","700-900");
so basically i want an array that will look like
array("0-100","200-400","500-700","900-10000");
for example-> if i started a value from 0 so it will break on 100.so i will get 0-100 as first element of an array,then nothing will happen until 200.Again 200 the value will start and go to 400 and will stop then i get 200-400.After that nothing will happen until 500.it will again start with 500 and will stop on 700.so i will get third element as 500-700 and so on...
Anybody can help?
if you want your ranges to be as string element of array, try this:
<?php
$b = array("400-500","700-900","100-200");
asort($b);//new line to sort the ranges
$MIN = 0;
foreach($b as $rang){
$limits = explode('-', $rang);
$result[] = $MIN." - ".$limits[0];
$MIN = $limits[1];
}
$result[] = $MIN." - 10000";
print_r($result);
?>
You can try something like this
<?php
$b = array( "100-200","400-500","700-900" );
$c = array();
$starting = 0;
$ending = 100000;
$last = $starting;
$a = array(); // not being used
$a = range( $starting, $ending ); // not being used
foreach( $b as $k => $v )
{
$values = explode( '-' , $v);
if ( $values[0] > $starting && $values[0] < $ending )
{
$c[] = $last.'-'.$values[0];
$last = $values[1];
if ( $last <= $ending && $k == count( $b ) -1 )
{
$c[] = $last.'-'.$ending;
}
}
}
print_r( $c );
?>
Please bear in mind that I did not use the original $a array for anything. I don't understand it's purpose, unless it's not actually generated from a range, and if so this could should be changed as well

Categories