Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find greatest of three values in PHP

Tags:

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;
}
like image 624
Gordon Avatar asked Jul 31 '09 00:07

Gordon


People also ask

How to compare 3 numbers in php?

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! Also you could do it just in one line max(max($x, $y), $z) .

How to find Greater number in php?

The max() function of PHP is used to find the numerically maximum value in an array or the numerically maximum value of several specified values. The max() function can take an array or several numbers as an argument and return the numerically maximum value among the passed parameters.

What is factorial number in php?

The factorial of a number n is defined by the product of all the digits from 1 to n (including 1 and n). For example, 4! = 4*3*2*1 = 24.


2 Answers

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.

like image 195
Greg Hewgill Avatar answered Sep 25 '22 18:09

Greg Hewgill


You can also use an array with max.

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

if you need to

like image 43
Tyler Carter Avatar answered Sep 22 '22 18:09

Tyler Carter