note 9213 deleted from control-structures.foreach by sniper

From: Date: Wed, 08 Oct 2003 04:12:31 +0000
Subject: note 9213 deleted from control-structures.foreach by sniper
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-58023@lists.php.net to get a copy of this message
Note Submitter: info@borderblue.com ---- As the documentation notes, and as another use pointed out above, foreach operates on a COPY of the array. I was trying to delete some elements from an ordered array and have the later elements shift automatically, using foreach, the below example DID NOT work: foreach ($blah as $key => $value) { if ($value < 1) { array_splice($blah,$key,1); reset($blah); } } I think the array_splice worked, but the reset didn't, so it would delete one element, but possibly miss others because $key would keep advancing. The code that seems to work is: reset($blah); while (list($key,$value) = each($blah)) { if ($value < 1) { array_splice($blah,$key,1); reset($blah); } }

« previous php.notes (#58023) next »