You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 $x into the array—instead, make this array element a pointer to the same memory location where $x is stored."
  • When you update $arr[0], you're writing directly to that shared memory space, so $x automatically 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 17:18:13