Unset an array element inside a foreach loop [dupl

2019-01-18 20:12发布

This question already has an answer here:

I'm accessing an array by reference inside a foreach loop, but the unset() function doesn't seem to be working:

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

print_r($this->result['list']); // Includes rows I thought I unset

Ideas? Thanks!

3条回答
手持菜刀,她持情操
2楼-- · 2019-01-18 20:39

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]);
    }
}
查看更多
Lonely孤独者°
3楼-- · 2019-01-18 20:43
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

查看更多
ら.Afraid
4楼-- · 2019-01-18 20:49

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.

查看更多
登录 后发表回答