# I honestly have no idea how to frame this cross-cutting title puzzle

So, this is what I see in this code:

• The cycle is repeated 10 times
• A new array is created
• The reference to this new array is stored in the first array
• 10 arrays are now in the original array with values ​​0, 1, 2, 3 ...

What's really going on:

• WTF?

code:

``````<?php

\$arrays = array();

foreach(range(0, 10) as \$i)
{
\$arr = array();
\$arr = \$i;

\$arrays[] = &\$arr;
}

print_r(\$arrays);
```

```

Output:

``````Array
(
 => Array
(
 => 10
)

 => Array
(
 => 10
)

 => Array
(
 => 10
)

 => Array
(
 => 10
)

 => Array
(
 => 10
)

 => Array
(
 => 10
)

 => Array
(
 => 10
)

 => Array
(
 => 10
)

 => Array
(
 => 10
)

 => Array
(
 => 10
)

 => Array
(
 => 10
)

)
```

```

I would like to know exactly why, apparently, only the 10th array is mentioned ten times, and not every instance of the arrays referring to each one.

Also, if someone who doesn't just think that WTF (like me) would like to edit the title, feel free to do so.

+3

source to share

Line

``````\$arr = array();
```

```

does not create a new array, but assigns an empty array to an already existing reference. If you want a variable name to "point" to another array in memory, you must first `unset()`

(or "disable") before assigning an empty array to it:

``````foreach(range(0, 10) as \$i)
{
unset(\$arr);
\$arr = array();
\$arr = \$i;

\$arrays[] = &\$arr;
}
```

```

This is because the only operations that can make a variable point to something else are reference assignment ( `=&`

) and `unset()`

.

+3

source

What happens is that by inserting a reference to `\$arr`

inside `\$arrays`

, you are actually adding the same array 10 times - and each reference to the array has the last value assigned to it (i.e. one when `\$i`

equal to 10).

It's not clear what you intend to achieve by inserting a reference into each iteration - either deleting `&`

or putting `unset(\$arr)`

at the beginning of the loop will give you the expected behavior. What are you trying to accomplish?

+1

source

Think of it this way. You do `\$arrays[] = &\$arr;`

10 times. This keeps the reference to the local variable `\$arr`

10 times. Since it is the same variable (the scope variable is an entire function), it stores the same reference all 10 times. So why should you expect the 10 elements to be different?

The link you are storing has nothing to do with the value `\$arr`

; it's just related to the variable `\$arr`

. When you print the link, the value is printed at that time `\$arr`

.

0

source

This is because you are storing an array reference that `\$arr`

points to an array. And you keep rewriting this array with the last number. All references in are `\$arr`

pointing to the same array at the end.

I don't know what you expect from this in the end, but getting rid of `&`

should fix this behavior.

-1

source

All Articles