...

View Full Version : the min() function



alex57
02-04-2007, 09:42 PM
hello,

I have three session variables:



$_SESSION['var1'] = "1";
$_SESSION['var2'] = "2";
$_SESSION['var3'] = "3";

If I then wanted to show the lowest numerical value here was 1 I could use:


echo min($_SESSION['var1'], $_SESSION['var2'], $_SESSION['var3']);


The answer would be 1. If I had the three variables again as below and wanted to know the minimum numerical value, the message echoed would be Gary. Why is this? Is there a function which finds the minimum and recognises the strings as strings and not integers? Can you test for a variable type?

Thanks




$_SESSION['var1'] = "1";
$_SESSION['var2'] = "gary";
$_SESSION['var3'] = "peter";

mlseim
02-04-2007, 09:46 PM
http://www.w3schools.com/php/func_math_min.asp

oh ... I guess you have more than two numbers ....

.

anarchy3200
02-04-2007, 09:58 PM
Not necessarily the best way of completion but:


function mini ( $nums ){
foreach ($nums AS $n){
if(is_numeric($n)===TRUE){
$numbers[] = $n;
}
}
return min($numbers);
}

echo mini(array($_SESSION['var1'], $_SESSION['var2'], $_SESSION['var3']));


Hope that helps.

chump2877
02-04-2007, 10:09 PM
if I had the three variables again as below and wanted to know the minimum numerical value, the message echoed would be Gary. Why is this?My best guess: Strings are the equivalent of the numeric zero, and "g" comes before "p", so the lowest value there according to the function is "gary"...


Is there a function which finds the minimum and recognises the strings as strings and not integers? Can you test for a variable type?you can use gettype() (http://us3.php.net/manual/en/function.gettype.php) to find the type of a variable before you compare them with the min() function...


Edit: Well maybe using gettype isn;t such a good idea:


Warning Never use gettype() to test for a certain type, since the returned string may be subject to change in a future version. In addition, it is slow too, as it involves string comparison. Instead, use the is_* functions.

then I would use is_numeric to find numeric values, like anarchy did...



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum