Reputation: 1914
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;
}
Upvotes: 17
Views: 47928
Reputation: 9203
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)
.
Upvotes: -1
Reputation: 11
<?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
Upvotes: 0
Reputation: 994231
Probably the easiest way is $c = max($x, $y, $z)
. See the documentation on max
Docs for more information, it compares by the integer value of each parameter but will return the original parameter value.
Upvotes: 30
Reputation: 61577
You can also use an array with max.
max(array($a, $b, $c));
if you need to
Upvotes: 12