PHP技术问询:如何通过数组位置引用修改原变量值?
Hey there! Let's break down why your original code isn't working and how to fix it.
Why your current code doesn't change $x
When you assign $x and $y to the array like array($x, $y), PHP creates copies of those variables' values and stores them in the array. So $arr[0] is just a duplicate of $x's original value, not linked to the actual $x variable. Changing the array element only modifies that copy, leaving $x untouched.
How to modify $x via the array (using references)
To make the array element point directly to the original $x variable (instead of a copy), you need to use the reference operator & when adding the variable to the array. Here's the adjusted code:
$x = 'hello world'; $y = 'bye world'; // Use & to store references to $x and $y in the array $arr = array(&$x, &$y); $arr[0] = 'new string'; var_dump($x); // Output: string(10) "new string"
What's happening here?
- The
&tells PHP: "Don't copy the value of$xinto the array—instead, make this array element a pointer to the same memory location where$xis stored." - When you update
$arr[0], you're writing directly to that shared memory space, so$xautomatically reflects the change.
A quick note
This works in PHP 5 and later. If you ever need to break the link between the array element and the original variable later, you can use unset($arr[0])—this removes the reference without affecting the original $x value.
内容的提问来源于stack exchange,提问作者Angel Esc

