PHP Reference ยท Math Functions
PHP max() and min() functions
Reference for PHP max() and min(): find the largest or smallest value in an array or argument list, mixed-type comparison rules and empty-array errors.
max() returns the largest value and min() the smallest. You can pass either a single array or two or more separate arguments. Both work on numbers, strings and arrays, and they return the original value, not a copy converted to a number.
Values are compared with the same rules as the <=> operator. That is harmless for plain numbers, but it can surprise you with mixed types or numeric strings, so keep the types in a list uniform.
<?php echo max(3, 9, 4); // 9 echo min([8, 2, 5]); // 2
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
max(mixed $value, mixed ...$values): mixed min(mixed $value, mixed ...$values): mixed
| Name | Description |
|---|---|
$value |
Either an array of values to examine, or the first of several values. |
...$values |
Further values to compare. Only allowed when $value is not an array. |
Return value: the largest (max) or smallest (min) value, with its original type.
Errors: a ValueError if you pass an empty array, or TypeError if a single non-array argument is given.
Usage notes
- One array or many arguments.
max($list)andmax(...$list)give the same result for a non-empty list. - Empty arrays throw. Before PHP 8.0 they returned
falsewith a warning. Guard against empty input or append a default value. - Ties return the first.
max(10, 10.0)returns the first one,10, so the type of the result can depend on argument order. - Mixed types follow the standard comparison rules. Numeric strings compare as numbers, and since PHP 8 a number is compared with a non-numeric string by turning the number into a string. Avoid mixing types.
- Arrays are compared by element count first, then value by value; an array is always larger than a scalar.
- Largest by a field:
max()can't take a callback. Usearray_column()to pull out the field, orarray_reduce(). - Position, not just value: use
array_search()on the result, orarray_keys($list, max($list)).