PHP 8.5.0 Alpha 2 available for testing

Voting

: max(one, one)?
(Example: nine)

The Note You're Voting On

Samu
1 year ago
With modern PHP versions supporting the array spread operator for function arguments, it's tempting to call max() like this:

<?php
function stuff(): iterable {
// This function might yield 0, 1 or n values.
}

$foo = max(...stuff());
?>

However, this is dangerous if you cannot guarantee that your generator yields **minimum** two values.

The gotcha here is that when max() receives a single argument, it must be an array of values. (When the generator doesn't yield any values, max() will throw an ArgumentCountError.)

If you can guarantee that your generator yields at least one value, then it's safe to call max by relying on the aforementioned array expectation:

<?php
function stuff(): iterable {
// This function will yield 1...n values.
}

// Note that here the generator is first read into an array.
$foo = max([...stuff()]);
?>

If the array is empty, max() will throw a ValueError.

The added burden is that faulty code could appear to appear to function just fine but fails at random, probably causing a lot of head-scratching at first.

<< Back to user notes page

To Top