Unset an array element inside a foreach loop [duplicate]

懵懂的女人 提交于 2019-11-28 10:51:43

You're unsetting the reference (breaking the reference). You'd need to unset based on a key:

foreach ($this->result['list'] as $key => &$row) {
    if ($this_row_is_boring) {
        unset($this->result['list'][$key]);
    }
}
foreach ($this->result['list'] as $key => &$row) {
    if ($this_row_is_boring) {
        unset($this->result['list'][$key]);
    }
}
unset($row);

Remember: if you are using a foreach with a reference, you should use unset to dereference so that foreach doesn't copy the next one on top of it. More info

A bit of an explanation to the answers above.

After unset($row) the variable $row is unset. That does not mean the data in $row is removed; the list also has an element pointing to $row.

It helps to think of variables as labels. A piece of data can have one or more labels, and unset removes that label but does not touch the actual data. If all labels are removed the data is automatically deleted.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!