【问题标题】:Calling array_splice/unset in a function: why does side effect not propagate?在函数中调用 array_splice/unset:为什么副作用不会传播?
【发布时间】:2018-11-28 11:48:55
【问题描述】:

我想使用 PHP 从数组中删除元素,发现使用 array_spliceunset 很容易。

我想在另一个函数中使用它,该函数将这个数组与要删除的元素作为参数。但是,该函数有一些其他返回值,并且该数组应该作为副作用进行更新(array_spliceunset 都通过副作用起作用)。我的代码如下所示:

<?php

function removeSomeElements($arr)
{
    for ($i = 0; $i<count($arr); $i++) {
        $c = $arr[$i];
        if ($c > 2) {
            echo "Element $c found at $i\n";
            unset($arr[$i]);
        }
    }
    print_r($arr);  // misses middle element
    return true;
}

$t = [0, 3, 1];

print_r($t);  // original array
$success = removeSomeElements($t);
print_r($t);  // should be missing middle element, but everything is here

我在使用 array_splice 时遇到了同样的问题,也就是说,当我将调用 unset 替换为以下内容时:

array_splice($arr, $i, 1);
$i--;

函数的参数在函数内部更新良好,但在外部没有。我错过了什么吗?


注意:我可以很容易地找到解决方法,我只是想知道这是否可行以及为什么/为什么不可行。提前致谢!

【问题讨论】:

  • 参考传递研究

标签: php arrays unset array-splice


【解决方案1】:

您需要通过reference &amp; 传递array

试试这样:

替换这一行:

function removeSomeElements($arr)

用这一行:

function removeSomeElements(&$arr)

Test

【讨论】:

  • 像魅力一样工作!
【解决方案2】:

另一种方法是在函数中返回更改后的数组,然后像这样设置$t 变量:

<?php

function removeSomeElements($arr)
{
    for ($i = 0; $i<count($arr); $i++) {
        $c = $arr[$i];
        if ($c > 2) {
            echo "Element $c found at $i\n";
            unset($arr[$i]);
        }
    }
    print_r($arr);  // misses middle element
    return $arr; // <-- return the altered array
}

$t = [0, 3, 1];

print_r($t);  // original array
$t = removeSomeElements($t); // <-- set the variable
print_r($t);

返回:

Array
(
    [0] => 0
    [1] => 3
    [2] => 1
)
Element 3 found at 1
Array
(
    [0] => 0
    [2] => 1
)
Array
(
    [0] => 0
    [2] => 1
)

https://3v4l.org/Jisfv

【讨论】:

  • 谢谢,这可行,但我尽量避免返回数组。
  • @BusyAnt 老兄别担心,去找第四只鸟的答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-15
  • 2017-04-15
相关资源
最近更新 更多