October 25, 2024
Chicago 12, Melborne City, USA
PHP

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.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video