Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unset an array element inside a foreach loop [duplicate]

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!

like image 715
Summer Avatar asked Jun 16 '10 15:06

Summer


People also ask

How do I remove an array from a foreach loop?

Use unset() function to remove array elements in a foreach loop. The unset() function is an inbuilt function in PHP which is used to unset a specified variable.

How do you unset an array?

Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.

Can you change a foreach loop?

Instead, changes are simply discarded at the end of each loop cycle. As a result we cannot modify the collection we loop over (Stephens, 2014). To prevent confusion with the foreach loop, don't bother with changing the loop variable inside the loop.


2 Answers

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]);
    }
}
like image 140
ircmaxell Avatar answered Oct 08 '22 08:10

ircmaxell


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

like image 29
Cristian Avatar answered Oct 08 '22 09:10

Cristian