So here’s what I see this code doing:
- An array is made
- A loop iterates 10 times
- A new array is created
- A reference to this new array is saved in the first array
- 10 arrays now reside in the original array with values 0, 1, 2, 3…
What really happens:
- WTF?
Code:
<?php
header('Content-type: text/plain');
$arrays = array();
foreach(range(0, 10) as $i)
{
$arr = array();
$arr[0] = $i;
$arrays[] = &$arr;
}
print_r($arrays);
Output:
Array
(
[0] => Array
(
[0] => 10
)
[1] => Array
(
[0] => 10
)
[2] => Array
(
[0] => 10
)
[3] => Array
(
[0] => 10
)
[4] => Array
(
[0] => 10
)
[5] => Array
(
[0] => 10
)
[6] => Array
(
[0] => 10
)
[7] => Array
(
[0] => 10
)
[8] => Array
(
[0] => 10
)
[9] => Array
(
[0] => 10
)
[10] => Array
(
[0] => 10
)
)
I would like to know exactly why apparently only the 10th array is referred to ten times, instead of every instance of the arrays being referred to one each.
Also if somebody who isn’t just thinking WTF (like me) would like to edit the title, feel free to do so.
The line
does not create a new array but rather assigns an empty array to the already existing reference.
If you want the variable name to “point” to a different array in memory, you have to
unset()(or “disconnect”) it first before assigning an empty array to it:This is because the only operations that can make a variable point to something else is the reference assignment (
=&) and theunset().