#42306 [Opn->Asn]: current/next/prev/key usage on the same array as foreach() is looping

From: Date: Wed, 15 Aug 2007 10:32:07 +0000
Subject: #42306 [Opn->Asn]: current/next/prev/key usage on the same array as foreach() is looping
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-116104@lists.php.net to get a copy of this message
ID: 42306 Updated by: jani@php.net Reported By: hannes dot magnusson at gmail dot com -Status: Open +Status: Assigned Bug Type: Arrays related Operating System: Linux/Ubuntu 7.04 PHP Version: 5CVS-2007-08-15 (CVS) -Assigned To: +Assigned To: dmitry New Comment: <?php $a = range('a', 'f'); echo "without reference:\n"; foreach($a as $b) { echo key($a), ' - ', current($a), "\n"; } echo "with reference:\n"; foreach($a as &$b) { echo key($a), ' - ', current($a), "\n"; } ?> Output: without reference: 1 - b 1 - b 1 - b 1 - b 1 - b 1 - b with reference: 1 - b 2 - c 3 - d 4 - e 5 - f - Previous Comments: ------------------------------------------------------------------------ [2007-08-15 09:19:53] hannes dot magnusson at gmail dot com Description: ------------ If I use current/next/prev/key() on the same array as foreach() is currently looping over the internal pointer is only increased on the first iteration. However. If I compare the value ($b) to something before using current/next/prev/key() I get the expected results: $a = range(0, 10); foreach($a as $b) { if($b == 5) { var_dump(current($a)); // int(6) } } Reproduce code: --------------- <?php $a = range(0, 10); foreach($a as $b) { var_dump(current($a)); if($b == 5) { var_dump(current($a)); } } Expected result: ---------------- int(1) int(2) int(3) int(4) int(5) int(6) // The var_dump() inside the if() int(6) int(7) int(8) int(9) int(10) bool(false) // Since the internal pointer points beyond the end Actual result: -------------- int(1) int(1) int(1) int(1) int(1) int(1) int(1) int(1) int(1) int(1) int(1) int(1) ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=42306&edit=1

« previous php.bugs (#116104) next »