Mathematics7 min readExamples run on PHP 8.5.10

max()

Learn how PHP 8.4 max() picks the highest value from arguments or an array, how mixed types compare, and which mistakes to avoid.

Signature

max(mixed $value, mixed ...$values): mixed
max(array $value_array): mixed

Purpose

max() answers a simple question: which of these values is the highest? You can hand it several separate values, or a single array that holds them. It returns the winning value unchanged, so an integer stays an integer and an array stays an array. Typical uses include finding the top score, clamping a lower bound, or picking the latest of several version numbers.

Signature

The second form is an alternative signature and is not supported with named arguments.

Parameters

  • value: any comparable value. When it is the only argument, it must be an array, and max() searches inside that array.
  • values: any number of additional comparable values. When at least two arguments are given in total, max() returns the largest of them.
  • value_array: the array form of the first parameter. It holds the values to compare.

None of the parameters has a default value. You must supply at least one array or at least two values.

Return value and failures

The function returns whichever input is considered highest under PHP's standard comparison rules. No conversion is applied to the result, so you get back the original value with its original type.

If several values of different types compare as equal, the first one you passed is returned. For example, 0 and false are equal, so max(0, false) gives 0 while max(false, 0) gives false.

Passing an empty array throws a ValueError. Since PHP 8.0.0 this is an exception; older versions returned false with a warning. A single argument that is not an array is also an error, because there is nothing to compare it with.

Example: numbers and arrays

The first example shows the two calling styles side by side. Notice that mixing an integer and floats returns the original winner, here the integer 2.

Example
<?php
echo json_encode([
    max(2, 3, 1, 6, 7),
    max([2, 4, 5]),
    max(-3, -8, -1),
    max(1.5, 2, 1.99),
]), PHP_EOL;
Output
[7,5,-1,2]

Example: arrays and strings as candidates

Arrays can be compared with each other. An array with fewer elements is smaller than one with more elements. When the lengths match, elements are compared from left to right until one differs. Non-numeric strings are compared as strings, so alphabetical order decides.

Example
<?php
$longest = max([2, 2, 2], [1, 1, 1, 1]);
$leftToRight = max([2, 4, 8], [2, 5, 1]);
$text = max('apple', 'banana', 'cherry');
echo json_encode([$longest, $leftToRight, $text]), PHP_EOL;
Output
[[1,1,1,1],[2,5,1],"cherry"]

Example: guarding against an empty array

Data often arrives as a list that might be empty. Decide in advance what an empty list should mean, then guard before calling max(). The second half of the script shows the exception you get when you do not.

Example
<?php
function highestOrNull(array $values): mixed
{
    if ($values === []) {
        return null;
    }
    return max($values);
}

echo json_encode([highestOrNull([4, 9, 2]), highestOrNull([])]), PHP_EOL;

try {
    max([]);
} catch (ValueError $e) {
    echo get_class($e), PHP_EOL;
}
Output
[9,null]
ValueError

Edge cases

  • Mixed types are risky. Standard comparison rules apply, and the manual warns that results can be unpredictable. Comparing a non-numeric string with an integer casts the integer to a string, so max('hello', -1) returns 'hello'.
  • Booleans and null. If one argument is null or a boolean, the comparison follows false < true regardless of the other types. In max(-10, false) the number -10 counts as true, so -10 wins. In max(0, true) the 0 counts as false, so true wins.
  • Arrays beat scalars. When an array and a non-array are compared, the array is treated as greater, so max('string', [2, 5, 7], 42) returns the array.
  • Ties. Equal values of different types return the first one supplied, as described above.

Common mistakes

  1. Calling max() on a list that may be empty without a guard, which causes an uncaught ValueError.
  2. Passing one scalar, such as max(5), expecting it to simply return 5. A single argument must be an array.
  3. Mixing strings, booleans and numbers in one call and trusting the outcome. Normalize your data to one type first, for example by casting numeric strings with (int) or (float).
  4. Expecting max() to give you a key. It returns only the value. If you need the position, use array_search() on the result or sort with a key-aware function.
  5. Forgetting that the array form takes one array. max($a, $b) with two arrays compares the arrays to each other; it does not search inside them.
  • min() finds the lowest value using the same comparison rules.
  • count() returns the number of elements, which is useful when checking for an empty array before calling max().
  • array_search() finds the key of a value once you know the maximum.

Recap

max() returns the highest of several values or of the values in one array, preserving the original type. Keep your inputs the same type, guard against empty arrays, and remember that ties across types return the first argument. In PHP 8 an empty array throws a ValueError.

Tested examples

Numbers and a single array
<?php
echo json_encode([
    max(2, 3, 1, 6, 7),
    max([2, 4, 5]),
    max(-3, -8, -1),
    max(1.5, 2, 1.99),
]), PHP_EOL;
Output
[7,5,-1,2]
Arrays and strings as candidates
<?php
$longest = max([2, 2, 2], [1, 1, 1, 1]);
$leftToRight = max([2, 4, 8], [2, 5, 1]);
$text = max('apple', 'banana', 'cherry');
echo json_encode([$longest, $leftToRight, $text]), PHP_EOL;
Output
[[1,1,1,1],[2,5,1],"cherry"]
Guarding against an empty array
<?php
function highestOrNull(array $values): mixed
{
    if ($values === []) {
        return null;
    }
    return max($values);
}

echo json_encode([highestOrNull([4, 9, 2]), highestOrNull([])]), PHP_EOL;

try {
    max([]);
} catch (ValueError $e) {
    echo get_class($e), PHP_EOL;
}
Output
[9,null]
ValueError