Bug #71073 [Nab]: Foreach behaviour changes allow for infinite loops

From: Date: Wed, 09 Dec 2015 10:06:15 +0000
Subject: Bug #71073 [Nab]: Foreach behaviour changes allow for infinite loops
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-197729@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=71073&edit=1 ID: 71073 Updated by: nikic@php.net Reported by: ljsteadman at gmail dot com Summary: Foreach behaviour changes allow for infinite loops Status: Not a bug Type: Bug Package: Performance problem Operating System: Any PHP Version: 7.0.0 Block user comment: N Private report: N New Comment: PHP 5 would not create a copy for by-reference iteration. That's pretty much the point of iterating by-reference, that you're working on the original array, not a copy of it. The foreach implementation in PHP 5 was simply broken and didn't handle this particular case correctly. With a slight change to your sample code you'll get an infinite loop in PHP 5 as well: https://3v4l.org/FX3Ld (Two starting elements instead of one) The foreach changes in PHP 7 are specified here: https://wiki.php.net/rfc/php7_foreach Previous Comments: ------------------------------------------------------------------------ [2015-12-09 09:54:13] ljsteadman at gmail dot com PHP 5.3 - PHP 5.6 would use a copy of the array, thus not producing an infinite loop. The change in behaviour is the concern here. ------------------------------------------------------------------------ [2015-12-09 09:48:41] nikic@php.net Foreach could always produce infinite loops. Both through iterators (InfiniteIterator), but also for arrays. The modifications you had to do were only different previously. If you don't want an infinite loop, don't grow your array infinitely... ------------------------------------------------------------------------ [2015-12-09 09:42:57] ljsteadman at gmail dot com Description: ------------ The latest behaviour changes to foreach means that if an element is pushed onto the array during iteration with a unique key, it will infinite loop. Test script: --------------- https://3v4l.org/ATFK9 Expected result: ---------------- foreach shouldn't produce a infinite loop. Actual result: -------------- foreach continues to iterate until it runs out of memory, thus producing an infinite loop. ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=71073&edit=1

« previous php.bugs (#197729) next »