|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2000-07-27 20:31 UTC] nathan at cjhunter dot com
If php is looping through an assoc array using the key() function the next element after an element has been unset is then skipped. I think the problem is the array pointer is not being set appropriately after the unset.
Here is below is an example of the behavior.
$a = array("a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5);
reset($a);
while($key = key($a)){
echo $key . "<br>\n";
if($a[$key] == 2){
unset($a[$key]);
}
next($a);
}
var_dump($a);
/*
This returns the below. Notice the "c" key is not given.
a
b
d
e
array(4) {
["a"]=>
int(1)
["c"]=>
int(3)
["d"]=>
int(4)
["e"]=>
int(5)
}
*/
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2026 The PHP GroupAll rights reserved. |
Last updated: Sat Oct 10 09:00:01 2026 UTC |
I do not believe that this is a bug. When you call unset, it shifts the elements under the unset element (if any) up to replace the missing space. So, c moves into b's spot, and then you call next... <? $a = array("a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5); reset($a); while($key = key($a)){ echo "Current key before unset: $key"; if($a[$key] == 2){ unset($a[$key]); } print ' | Current key after unset '. key ($a) . '<br />'; next($a); } print '<pre>'; var_dump($a); print '</pre>'; ?>