7

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?

Unheilig
  • 15,944
  • 193
  • 67
  • 96
Florin Frătică
  • 577
  • 4
  • 7
  • 13
  • 2
    possible duplicate of [How do you remove an array element in a foreach loop?](http://stackoverflow.com/questions/1949259/how-do-you-remove-an-array-element-in-a-foreach-loop) – 7hi4g0 Jan 29 '14 at 06:47

3 Answers3

26

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]);
    }
}
NikiC
  • 98,796
  • 35
  • 186
  • 223
  • But what if you add an `&` sign before `$row` (Pass by reference) ? –  Jul 15 '14 at 14:40
3

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);
hakre
  • 184,866
  • 48
  • 414
  • 792
Marc B
  • 348,685
  • 41
  • 398
  • 480
  • 2
    Reference won't work btw. It will still only be a local variable. ;) – NikiC Jan 20 '12 at 14:36
  • Additionally it's good practise to put the `unset($val)` after the `foreach` loop to remove the reference (this would spare the last paragraph of the answer as well). – hakre Jan 28 '12 at 19:40
0

Because $row is the value, not the entire element.

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

CompanyDroneFromSector7G
  • 3,987
  • 12
  • 51
  • 92