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

Add a Patch

Pull Requests

Add a Pull Request

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-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 11:01:27 2024 UTC