note 128947 added to function.max

From: Date: Thu, 12 Oct 2023 07:28:28 +0000
Subject: note 128947 added to function.max
Groups: php.notes 
Request: Send a blank email to php-notes+get-220906@lists.php.net to get a copy of this message
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. ---- Server IP: 45.112.84.4 Probable Submitter: 45.91.157.134 (proxied: 115.87.151.123) ---- Manual Page -- https://php.net/manual/en/function.max.php Edit -- https://main.php.net/note/edit/128947 Del: integrated -- https://main.php.net/note/delete/128947/integrated Del: useless -- https://main.php.net/note/delete/128947/useless Del: bad code -- https://main.php.net/note/delete/128947/bad+code Del: spam -- https://main.php.net/note/delete/128947/spam Del: non-english -- https://main.php.net/note/delete/128947/non-english Del: in docs -- https://main.php.net/note/delete/128947/in+docs Del: other reasons-- https://main.php.net/note/delete/128947 Reject -- https://main.php.net/note/reject/128947 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#220906) next »