Unset an array element inside a foreach loop

Summer picture Summer · Jun 16, 2010 · Viewed 12.5k times · Source

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!

Answer

ircmaxell picture ircmaxell · Jun 16, 2010

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]);
    }
}