Vincent Dapiton
Vincent Dapiton

Reputation: 587

PHP : get the highest and lowest value among variables

Is their any way to get the highest and lowest value among variables?

example is that i have this variables

$val1 = 10
 $val2 = 20
 $val3 = 30
 $val4 = 40
 $val5 = 50

and among this variable i want to display or put to another variable the variable that has the highest and lowest value. just like below.

$highval = $val5; 
$lowval = $val1;

$val5 in $highval coz it has the value of 50 and $val1 in $lowval coz it has the value of 10 .

thanks

Upvotes: 0

Views: 1423

Answers (3)

Babis K.
Babis K.

Reputation: 7

well maybe you already find the solution ...

variables must not include numbers like your example

$val1 = 10;
$val2 = 20;
$val3 = 30;
$val4 = 40;
$val5 = 50;

$arr = compact('val1 ', 'val2 ', 'val3 ', 'val4 ', 'val5 ');
$highval = max($arr);
$lowval = min($arr);
echo "$lowval"; //  give val1 the first variable value In brackets inside
echo "$highval"; // give val5 the last variable value In brackets inside

lowval  is val1 (10)
highval is val5 (50)
The above example will give correct results 
(you got the right results because it happened 
to have the values ​​in ascending order).
WHY IS THIS WRONG !!! 
see below

PLEASE NOTE If the data comes from a database or an xml file then the values ​​are dynamic and not ascending, in this case we will get back the wrong results.

$val1 = 20;
$val2 = 30;
$val3 = 10;
$val4 = 50;
$val5 = 40;

$arr = compact('val1 ', 'val2 ', 'val3 ', 'val4 ', 'val5 ');
$highval = max($arr);
$lowval = min($arr);
 echo"$lowval"; // val1 give the first variable value In brackets inside
 echo"$highval"; // val5 give the last variable value In brackets inside

The above example will give wrong results 
lowval is val1 (20)
highval isval5 (40)
The right results are
lowval=val3 (10)
highval=val4 (50)

A simple solution is to replace the numbers with letters

$val1 = 30;
$val2 = 10;
$val3 = 50;
$val4 = 40;
$val5 = 20;

$vala = "$val1";
$valb = "$val2";
$valc = "$val3";
$vald = "$val4";
$vale = "$val5";

$arr = compact('vala ', 'valb ', 'valc ', 'vald ', 'vale ');
$highval = max($arr);
$lowval = min($arr);

now the results is correct

 echo "$lowval"; // give valb the lower value
 echo "$highval"; // give valc the higher value

Now the results is correct 
lowval is valb (10)
highval is valc (50)

Upvotes: 0

Indrasis Datta
Indrasis Datta

Reputation: 8606

When you are comparing a list of values, it's the best to store them in an array.

Try this:

$val1 = 10;
$val2 = 20;
$val3 = 30;
$val4 = 40;
$val5 = 50;

$arr = compact('val1','val2','val3','val4','val5');  // Stores values in array $arr
$highval = max($arr); // 50
$lowval  = min($arr);  // 10

Upvotes: 1

Gerrit Luimstra
Gerrit Luimstra

Reputation: 532

My suggestion is to put the scores in an array, like so:

$scores = array(1, 2, 4, 5);
$highest = max($scores);
$lowest = min($scores);

Upvotes: 3

Related Questions