php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #43988 Problems with foreach'ing on arrays with referenced element
Submitted: 2008-01-31 03:28 UTC Modified: 2008-02-20 14:48 UTC
Votes:1
Avg. Score:4.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:0 (0.0%)
From: claim at interia dot pl Assigned: dmitry (profile)
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.2.5 OS: Linux 2.6.23
Private report: No CVE-ID: None
 [2008-01-31 03:28 UTC] claim at interia dot pl
Description:
------------
The problem is that when you reference an array element (say, n) and then use the same name (as the reference) as the current element value alias inside foreach, two things happen:
1. inside the foreach body the n element is replaced with the n-1 element;
2. and after the foreach run the n element is replaced with the last array element.

Reproduce code:
---------------
<?php
$arr = array();
for ($i = 0; $i < 4; ++$i) {
	$arr[$i] = $i;	
}

$el = &$arr[2];

print_r($arr);
foreach ($arr as $el) {
	echo "el: $el\n";
}
print_r($arr);

?>

Expected result:
----------------
Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
)
el: 0
el: 1
el: 2
el: 3
Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
)

Actual result:
--------------
Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
)
el: 0
el: 1
el: 1
el: 3
Array
(
    [0] => 0
    [1] => 1
    [2] => 3
    [3] => 3
)

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-02-20 14:48 UTC] dmitry@php.net
This is not a big but expected result.
On each iteration foreach() assigns element of $arr into $el, but $el is a reference to $arr[2], so on each iteration you update $arr[2].

It is clear that in the end of loop $el and $arr[2] will be equal to the last element. The value of el == 1 on the third iteration can be explained too.

 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed Jun 26 16:01:30 2024 UTC