min() and max()
Have an array of values and need to find the largest or smallest value? No need to roll your own, PHP has functions for that built in.
Pretty simple, use min() to find find the smallest value, and use max() to find the largest. Keep in mind how PHP handles comparison. The usual “gotcha” of comparing strings with integers applies here.
$a = array(40, 87, 3952, 248, -34, 17); $min = min($a); // -34 $max = max($a); // 3952 // can simply pass multiple values not in an array $min = min(215, 236, 768, 39, 72); // 39 $max = max(43, 82, 674, 345); // 674 // comparing strings with integers $min = min(5, 'monkey', 82); // 'monkey' (evaluated as zero) $min = min(5, '17monkey', 82); // 5 ('17monkey' evaluated as 17)
When comparing arrays, the number of elements are compared. With arrays of equal size, PHP will compare them element by element from left to right.
// number of elements compared $a = array(40, 3298); $b = array(40, 983, 432); $min = min($a, $b); // array(40, 3298) $max = max($a, $b); // array(40, 983, 432) // arrays of equal count are compared left to right $c = array(1, 3); $min = min($a, $c); // array(1, 3); $max = max($a, $c); // array(40, 3298); $min = min($a, $b, $c); // array(1, 3); $max = max($a, $b, $c); // array(40, 983, 432)
And though it’s not in the documentation as of this writting, these functions can compare dates. (YYYY-MM-DD)
$a = '2008-04-17'; $b = '2008-08-03'; $min = min($a, $b); // '2008-04-17' $max = max($a, $b); // '2008-08-03'
