php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #5822 key() skips the next key if element previously unset
Submitted: 2000-07-27 20:31 UTC Modified: 2000-07-30 12:54 UTC
From: nathan at cjhunter dot com Assigned:
Status: Closed Package: Misbehaving function
PHP Version: 4.0.0 OS: Linux 2.0.28
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: nathan at cjhunter dot com
New email:
PHP Version: OS:

 

 [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)
}


*/

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2000-07-27 21:03 UTC] zak@php.net
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>';

?>

 [2000-07-30 12:54 UTC] stas@php.net
BTW, you can use foreach which won't have this effect.
 
PHP Copyright © 2001-2026 The PHP Group
All rights reserved.
Last updated: Sat Oct 10 10:00:02 2026 UTC