gpt4 book ai didi

PHP foreach删除数组元素

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:52 24 4
gpt4 key购买 nike

今天,在为博客开发文本分析工具时,我发现 PHP 的行为对我来说很奇怪,我无法理解它。在规范化文本时,我试图删除低于最小长度的单词,所以我在规范化方法中这样写:

if ($this->minimumLength > 1) {
foreach ($string as &$word)
{
if (strlen($word) < $this->minimumLength) {
unset($word);
}
}
}

奇怪的是,这会在我的数组中留下一些低于允许长度的词。在全类查找错误后,我试了一下:

if ($this->minimumLength > 1) {
foreach ($string as $key => $word)
{
if (strlen($word) < $this->minimumLength) {
unset($string[$key]);
}
}
}

瞧!这非常有效。现在,为什么会发生这种情况?我查看了PHP Documentation它指出:

If a variable that is PASSED BY REFERENCE is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

foreach 在这里充当调用环境 是因为它有自己的作用域吗?

最佳答案

不,这里没有函数调用,也没有通过引用传递变量(您只是在迭代期间通过引用捕获)。

当您通过引用迭代时,迭代变量是原始变量的别名。当您使用此别名来引用原始值并修改其值时,更改将在迭代的数组中保持可见。

但是,当您取消设置 别名时,原始变量并没有被“销毁”; 别名 只是从符号表中删除。

foreach ($string as $key => &$word)
{
// This does not mean that the word is removed from $string
unset($word);

// It simply means that you cannot refer to the iteration variable using
// $word from this point on. If you have captured the key then you can
// still refer to it with $string[$key]; otherwise, you have lost all handles
// to it for the remainder of the loop body
}

关于PHP foreach删除数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14296838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com