17

With three numbers, $x, $y, and $z, I use the following code to find the greatest and place it in $c. Is there a more efficient way to do this?

$a = $x;
$b = $y;
$c = $z;
if ($x > $z && $y <= $x) {
    $c = $x;
    $a = $z;
} elseif ($y > $z) {
    $c = $y;
    $b = $z;
}
Gordon
  • 1,844
  • 4
  • 17
  • 32
  • Related: [PHP Type-Juggling and (strict) Greater/Lesser Than Comparisons](http://stackoverflow.com/q/15813490/367456) – hakre Apr 07 '13 at 10:13

4 Answers4

30

Probably the easiest way is $c = max($x, $y, $z). See the documentation on maxDocs for more information, it compares by the integer value of each parameter but will return the original parameter value.

hakre
  • 193,403
  • 52
  • 435
  • 836
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
12

You can also use an array with max.

max(array($a, $b, $c));

if you need to

hakre
  • 193,403
  • 52
  • 435
  • 836
Tyler Carter
  • 60,743
  • 20
  • 130
  • 150
0
<?php
$a=20;
$b=10;
$c=1;
if($a>$b && $a>$c)
{
echo "Greater value is a=".$a;
}
else if($b>$a && $b>$c)
{
echo "Greater value is b=".$b;
}
else if($c>$a && $c>$b)
{
echo "Greater value is c=".$c;
}
else
{
echo"Dont Enter Equal Values";
}
?>

Output:

Greater value is a=20
Grant Miller
  • 27,532
  • 16
  • 147
  • 165
-1

If you want to Compare Three Variables. Compare two integers and get maximum of them by using max() function. Then compare the maximum with the third variable!

$x = 1; $y = 2; $z = 3;
$maximum = max($x, $y);
$c = max($maximum, $z);
echo $c; //3

Also you could do it just in one line max(max($x, $y), $z).

XMehdi01
  • 5,538
  • 2
  • 10
  • 34