note 127680 added to function.range
| From: | dewi at dewimorgan dot com | Date: | Wed, 28 Sep 2022 17:59:17 +0000 |
| Subject: | note 127680 added to function.range | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-219628@lists.php.net to get a copy of this message | ||
While it appears just like a convenient way to avoid the boilerplate of for(), beware that this is
not an iteration operator, despite its similarity to other languages which do have virtual
iterators.
Instead it is a literal array-filling operator, just like array_fill()! Use of range() for
generating a simple loop tends to be a code smell, and especially where the range values are
variable, it should probably be rejected in code review with a note to replace with for().
In particular, it is unsafe to do things like:
// Sanitize user input.
$max = intval($userInputMax);
// Loop over the range.
foreach(range(1, $max)) { ... do stuff ... }
If the user enters a large value like "1e9", this won't just loop for a long time:
it'll also allocate a gigabyte, then fill it with a range of incrementing integers. This often
results in a segfault.
Instead, avoid the array-allocation overhead with the faster and more idiomatic:
for ($i = $min; $i <= $max; $i += $step) {}
Equally, I've debugged production code which did the following, which takes several minutes
with a $max like 1e9, and will segfault if it's much larger than that (even with values well
below 2^32!):
$numItems = count(range($min, $max, $step));
This can instead be rewritten in a more secure, idiomatic and performant way, which takes just
microseconds and can also safely handle vastly larger numbers:
$numItems = ($max - $min) % $step;
----
Server IP: 45.112.84.4
Probable Submitter: 185.85.3.173 (proxied: 47.221.215.25)
----
Manual Page -- https://php.net/manual/en/function.range.php
Edit -- https://main.php.net/note/edit/127680
Del: integrated -- https://main.php.net/note/delete/127680/integrated
Del: useless -- https://main.php.net/note/delete/127680/useless
Del: bad code -- https://main.php.net/note/delete/127680/bad+code
Del: spam -- https://main.php.net/note/delete/127680/spam
Del: non-english -- https://main.php.net/note/delete/127680/non-english
Del: in docs -- https://main.php.net/note/delete/127680/in+docs
Del: other reasons-- https://main.php.net/note/delete/127680
Reject -- https://main.php.net/note/reject/127680
Search -- https://main.php.net/manage/user-notes.php