note 42576 deleted from control-structures.foreach by danbrown

From: Date: Tue, 28 Apr 2009 13:11:48 +0000
Subject: note 42576 deleted from control-structures.foreach by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153929@lists.php.net to get a copy of this message
Note Submitter: turadg at berkeley dot edu ---- The documentation above says "the internal pointer of the original array is advanced with the processing of the array". In my experience, it's more complicated than that. Maybe it's a bug in 4.3.2 that I'm using. If the array variable is created by =& assignment, then it works as described. You can use current() within the loop to see the next element. If the array variable is created by an = assignment, the foreach() doesn't advance the pointer. Instead you must use next() within the loop to peek ahead. The code below demonstrates. On my system, the output is the same for both blocks, though one uses next() and the other current(). <?php $originalArray = array("first", "second", "third", "fourth", "fifth"); print "the array:\n"; print_r($originalArray); print "\noriginalArray with next():\n"; foreach ($originalArray as $step) { $afterThis = next($originalArray); print "$step,$afterThis\n"; } $aliasArray =& $originalArray; print "\naliasArray with current():\n"; foreach ($aliasArray as $step) { $afterThis = current($aliasArray); print "$step,$afterThis\n"; } ?>

« previous php.notes (#153929) next »