Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting an array element within foreach loop

Tags:

php

I have a simple array which contains name of all the countries and total number of users registered on my website from that each country. It's something like this:

Array (
    [1] => Array ( [name] => Afghanistan [total] => 3 )
    [2] => Array ( [name] => Albania [total] => 0 )
)

And, I'm trying to delete array elements (countries) which have 0 users.

I've tried with this code and it's not working:

foreach($country as $row) {
    if ($row['total'] == 0) {
        unset($row);
    }
}

What is wrong with this code?

like image 301
Florin Frătică Avatar asked Jan 20 '12 14:01

Florin Frătică


People also ask

Can we remove an element by using foreach loop?

Can we remove an element by using forEach loop? The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove .

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

Can you modify array in foreach?

Note that foreach does not modify the internal array pointer, which is used by functions such as current() and key(). It is possible to customize object iteration. In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

How do you remove an element from an array index?

You can remove the element at any index by using the splice method. If you have an array named arr it can be used in this way to remove an element at any index: arr. splice(n, 1) , with n being the index of the element to remove. The splice method can accept many arguments.


2 Answers

If you unset($row) you are only removing the local variable.

Instead fetch the key and remove that:

foreach ($country as $i => $row) {
    if ($row['total'] == 0) {
        unset($country[$i]);
    }
}
like image 133
NikiC Avatar answered Oct 11 '22 17:10

NikiC


Foreach creates copies of the keys/values on the array you're looping over, so all you're doing is unsetting the local copy, not the original that's actually in the array. Either access the array directly

foreach($country as $key => $row) {
  if ($row['total'] == 0) {
     unset($country[$key]);
  }
}

or use a reference, unset it and filter NULL elements afterwards:

foreach($country as &$row) {
    if ($row['total'] == 0) {
        $row = (unset) $row;
    }
}
unset($row);
$country = array_filter($country);
like image 27
Marc B Avatar answered Oct 11 '22 18:10

Marc B