Skip to content
Advertisement

Find greatest of three values in PHP

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;
}

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement