php - I honestly have no clue how to formulate this pass-by-reference conundrum
Get the solution ↓↓↓Solution:
The line
$arr = array();
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 tounset()
(or "disconnect") it first before assigning an empty array to it:
foreach(range(0, 10) as $i)
{
unset($arr);
$arr = array();
$arr[0] = $i;
$arrays[] = &$arr;
}
This is because the only operations that can make a variable point to something else is the reference assignment (=&
) and theunset()
.
Answer
Solution:
What happens here is that by inserting a reference to$arr
inside$arrays
, you are effectively adding the exact same array 10 times -- and each reference to the array has the value last assigned to it (i.e. the one produced when$i
is 10).
It's not clear what you intend to achieve by inserting a reference in each iteration -- either removing the&
or puttingunset($arr)
at the beginning of the loop would give you the expected behavior. What are you trying to accomplish?
Answer
Solution:
Think about it this way. You do$arrays[] = &$arr;
10 times. This stores a reference to the local variable$arr
10 times. Since it's the same variable (the variable's scope is the entire function), it stores the same reference all 10 times. Thus, why should you expect the 10 elements to be different?
The reference you are storing has nothing to do with the value of$arr
; it just has to do with the variable$arr
. When you print the reference it prints the value of$arr
at that time.
Answer
Solution:
It's because you're storing a reference to the array that$arr
points to in the array. And you keep overwriting that array with the latest number. All references in$arr
will point to the same array in the end.
I don't know what you expect to get out of this in the end, but getting rid of&
should fix this behavior.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: uncaught error: call to undefined function mysqli_connect()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.