phparraysforeachreference

foreach by reference doesn't work if variable is assigned right in foreach definition


Could someone please explain why these two code snippets return different values?

$z = [[1,2,3],[4,5,6]];
foreach($z as &$i)
{
    $i[] = 6;
}
echo json_encode($z), "\n";; // prints [[1,2,3,6],[4,5,6,6]]

// VS    

foreach($z = [[1,2,3],[4,5,6]] as &$i)
{
    $i[] = 6;
}
echo json_encode($z), "\n"; // prints [[1,2,3],[4,5,6]] 

I would have expected the assigning of $z to the array would happen before the foreach either way, but something about putting the assignment within the foreach causes the array stored in $z to not be affected by appending to the end of the $i array.


Solution

  • The value of an assignment expression is the expression being assigned, not a reference to the variable that it was assigned to. So your second version is equivalent to:

    $temp_z = [[1,2,3],[4,5,6]];
    $z = $temp_z;
    foreach ($temp_z as &$i) {
        $i[] = 6;
    }
    

    So the reference is to the temporary array holding the literal value, not the array in $z.