Web Hosting Talk







View Full Version : [PHP] Workout which variable has the highest number


latheesan
04-05-2008, 10:13 PM
Hello,

I will do a series of complex calculation and at the end, these three variables have a number assigned to them like this :

$var_1 = 26;
$var_2 = 41;
$var_3 = 37;

What would be the quickest way to see, out of the three variables $var_1 and $var_2 and $var_3, which variable holds the highest number amonst the rest of the variables (without using a series of IF and ELSE) ?

csparks
04-05-2008, 10:36 PM
Not sure what context you are doing this in but you could do:


$array = array(26,41,37);

$sorted = sort($array,"SORT_NUMERIC");

//$sorted will return something like
$sorted[0] = 26;
$sorted[1] = 37;
$sorted[2] = 41;



I do not have time to test and make sure that is right up there, but you get the idea.

latheesan
04-05-2008, 11:10 PM
ah, thanks allot, this will be good enough :)

Adam-AEC
04-05-2008, 11:50 PM
Another option is to use the max() function.


$max = max(array($var_1, $var_2, $var_3));

csparks
04-05-2008, 11:53 PM
max will only return the highest value, and I think he wants it ordered from lowest to highest.

edit: oops misread the post, sorry to the post above and the op.

Adam-AEC
04-06-2008, 12:41 AM
I re-read it as well and think we were both wrong. From the sounds of it he wants to know the _variable_ that holds the highest integer, not the integer itself.

Anyways, with a little trickery the solution cometh.


function max_value() {
$args = func_get_args();

$values = array();
foreach ($args as $arg) { global $$arg; $values["$arg"] = $$arg; }
foreach ($values as $key => $value) if ($value == max($values)) return $key;
}

$val_1 = 26;
$val_2 = 41;
$val_3 = 37;

echo max_value('val_1', 'val_2', 'val_3');

latheesan
04-08-2008, 01:27 PM
Thank you so much Adam, this is exactly what i was looking for :)