It is a little wired for Java and .NET developer, but PHP by default returns a copy of the iterated array item when running a foreach statement.
From the official PHP site – Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don’t rely on the array pointer during or after the foreach without resetting it.
Here is a wrong way to manipulate an item in an array:
$arr1 = array(1, 2, 3, 4);
$arr2 = array(1, 2, 3, 4);
$arr = array(arr1,arr2);
foreach ($arr as $value) {
//add an element to the inner array
$value[] = 5;
}
The $value is a copy of the item and the changed do not affect the item in the array itself.
Java and .NET developers, like myself, scratch their head and say “why doesn’t the foreach work?” or “what doesn’t the items in the foreach change?”
the answer is you need to use the & sign to let PHP know you need a reference rather then a value.
So here is the correct way to do the same thing:
$arr1 = array(1, 2, 3, 4);
$arr2 = array(1, 2, 3, 4);
$arr = array(arr1,arr2);
foreach ($arr as &$value) {
//add an element to the inner array
$value[] = 5;
}