更新函数中的全局数组


update a global array within a function

我有一个全局数组,我试图在其中更新一个值(保持持久),然后显示它。
我没有得到错误,但数组永远不会更新。

<?php
$anchor = 'bird';
$stuff = array('apple', 'bird', 'frog');
function insert($anchor, $stuff){
    foreach($stuff as $part){
        $new_array = array($anchor => rand());
        if($part == $anchor){
            array_push($stuff, $new_array);
        }
    }
}
for($x = 0; $x < 2; $x++){
    insert($anchor, $stuff);
    var_dump($stuff);
}
输出:

array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(4) "bird"
  [2]=>
  string(4) "frog"
}
array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(4) "bird"
  [2]=>
  string(4) "frog"
}
预期输出:

{'bird' => 674568765}
{'bird' => 986266261}

如何在函数中更新数组,以便全局(持久)反映更改?

通过引用传递变量$stuff。注意功能参数中的&

function insert($anchor, &$stuff){    // note the & mark
        foreach($stuff as $part){
                $new_array = array($anchor => rand());
                if($part == $anchor){
                        array_push($stuff, $new_array);
                }
        }
}

正如其他人所提到的:默认情况下,PHP函数参数通过值传递,这意味着在函数内部更改的值不会在函数外部更改。

我建议从你的函数返回新的$stuff值:

<?php
$anchor = 'bird';
$stuff = array('apple', 'bird', 'frog');
function insert($anchor, $stuff){
  foreach($stuff as $part){
    $new_array = array($anchor => rand());
    if($part == $anchor){
      array_push($stuff, $new_array);
    }
  }
  return $stuff;
}
for($x = 0; $x < 2; $x++){
  $stuff=insert($anchor, $stuff);
}
echo"<pre>".print_r($stuff,true)."</pre>";
?>
Array
(
    [0] => apple
    [1] => bird
    [2] => frog
    [3] => Array
        (
            [bird] => 618490127
        )
    [4] => Array
        (
            [bird] => 1869073273
        )
)

其他解决方案建议通过引用传递,我不反对。但是我确实遇到过有bug的代码,其中不能立即清楚地知道函数正在更改值,并且我对意外的循环行为感到困惑。因此,我通常更喜欢返回新值的更具可读性/可维护性的代码。

参见在PHP中何时按引用传递。
和Sara Golemon玩技术游戏

如果您希望对传递给函数的变量的更改在函数结束后持续存在,请通过引用传递该变量:

改变:

function insert($anchor, $stuff)

function insert($anchor, &$stuff)