Anormal comportement with reference value in foreach

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I spend 2 hours to find an anormal comportement in foreach that make
fail my application.

Very simplified source code :

    $tab1 = array(1, 2, 3);
    $tab2 = array(1, 2, 3);

    //We use a reference here to simplify the change of array's value.
    foreach($tab1 as &$val)


    foreach($tab2 as $val)
        //Do nothing


    foreach($tab2 as $val)
        echo $val.' - '.$tab1[2]."\n"; //In order to show the value of
$tab1[2] changing at the same time that $val.

In this script, the 2 print_r() should print the same thing because we
don't modifing the $tab1 value;
But there not.

We can see that $tab1[2] still connected with $val variable.

But it's anormal : all row of $tab1 should still be connected or no

Re: Anormal comportement with reference value in foreach

Laurent wrote:
Quoted text here. Click to load it

This is described by (closed
bogus).  Your problem is that $val still retains the reference to
$tab1[2] throughout the rest of your code.



after the first loop resets the reference and provides the desired results.

Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.

Site Timeline