I'm using the following to discover the largest integer from 3 values.
<?php
$a = 100;
$b = 200;
$c = -300;
$max = max($a,$b,$c);
foreach( array('a','b','c') as $v) {
if ($$v == $max) {
echo "\$$v is $max and therefore the largest";
break;
}
}
?>
This works perfectly with the output: $b is 200 and therefore the largest
However, I would now like to also output the 2 smallest integers from the 3.
So as well as showing the 1 largest, it would also output the 2 others.
Can someone show me how I can achieve this?
Many thanks for any pointers.
To illustrate Matt answer :
$list = array(2, 3, 1);
sort($list);
echo "Largest element : ".$list[count($list)-1]."
";
echo "Two smallest elements :";
for($i=0; $i<2; $i++) {
echo $list[$i]." ";
}
$nums = array(100,200,-300);
sort($nums);
$twoSmallest = array_slice($sorted,0,2);
$largest = array_slice($sorted,-1,1);
I agree with the rest of the "sort it!" crowd. Here's a complete example where the name of the variables involved are kept, so the result is like the one in your example:
function var_cmp($_a, $_b) {
global $$_a, $$_b;
return $$_b - $$_a;
}
$a = 100;
$b = 200;
$c = -300;
$result = array('a', 'b', 'c');
usort($result, 'var_cmp');
printf('$%s is %d and largest, followed by $%s = %d and $%s = %d',
$result[0], ${$result[0]},
$result[1], ${$result[1]},
$result[2], ${$result[2]});