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!
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With