php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #53824 Array pointer unwanted reset
Submitted: 2011-01-23 20:06 UTC Modified: 2015-04-07 16:57 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:0 of 0 (0.0%)
From: php-guru at shark dot kom dot cz Assigned: nikic (profile)
Status: Closed Package: Arrays related
PHP Version: 5.3.5 OS: Win XP, Win 7
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: php-guru at shark dot kom dot cz
New email:
PHP Version: OS:

 

 [2011-01-23 20:06 UTC] php-guru at shark dot kom dot cz
Description:
------------
When looping by foreach on 2D array instead of it's array keys inner arrays' internal pointer is reset.

Test script:
---------------
<?php

$outer = array(
	'A' => array(0 => '1st', 1 => '2nd',                   3 => '3rd'),
	'B' => array(            1 => '2nd', 2 => 'still 2nd', 4 => '3rd', 5 => 'still 3rd'),
);
$syncMarks = array(1, 3);

do {
	$next = FALSE;
	$current = array();
	$syncMark = current($syncMarks);
	
	//foreach (array_keys($outer) as $key) {
	foreach ($outer as $key => $inner) {
		$offset = key($outer[$key]);
		
		if (isset($offset)) {
			$next = TRUE;
			
			if ($syncMark === FALSE || $offset < $syncMark) {
				$current[$key] = current($outer[$key]);
				next($outer[$key]);
			}
		}
	}
	
	var_dump($current);
} while (empty($current) && next($syncMarks) || $next);

Expected result:
----------------
array(1) {
  ["A"]=>
  string(3) "1st"
}
array(0) {
}
array(2) {
  ["A"]=>
  string(3) "2nd"
  ["B"]=>
  string(3) "2nd"
}
array(1) {
  ["B"]=>
  string(9) "still 2nd"
}
array(0) {
}
array(2) {
  ["A"]=>
  string(3) "3rd"
  ["B"]=>
  string(3) "3rd"
}
array(1) {
  ["B"]=>
  string(9) "still 3rd"
}
array(0) {
}


Actual result:
--------------
array(1) {
  ["A"]=>
  string(3) "1st"
}
array(0) {
}
array(2) {
  ["A"]=>
  string(3) "2nd"
  ["B"]=>
  string(3) "2nd"
}
array(1) {
  ["B"]=>
  string(9) "still 2nd"
}
array(0) {
}
array(2) {
  ["A"]=>
  string(3) "3rd"
  ["B"]=>
  string(3) "3rd"
}
array(2) {
  ["A"]=>
  string(3) "1st" // <-- This is unwanted result
  ["B"]=>
  string(9) "still 3rd"
...

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-04-07 16:57 UTC] nikic@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: nikic
 [2015-04-07 16:57 UTC] nikic@php.net
In PHP 7 foreach will no longer modify the internal array pointer.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Sat Jul 12 13:01:33 2025 UTC