ID:               43988
 Updated by:       [EMAIL PROTECTED]
 Reported By:      claim at interia dot pl
-Status:           Open
+Status:           Bogus
 Bug Type:         Scripting Engine problem
 Operating System: Linux 2.6.23
 PHP Version:      5.2.5
-Assigned To:      
+Assigned To:      dmitry
 New Comment:

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.



Previous Comments:
------------------------------------------------------------------------

[2008-01-31 03:28:11] 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
)


------------------------------------------------------------------------


-- 
Edit this bug report at http://bugs.php.net/?id=43988&edit=1

Reply via email to