tags:

views:

230

answers:

2

I have a normal array like this

Array
(
    [0] => 0
    [1] => 150
    [2] => 0
    [3] => 100
    [4] => 0
    [5] => 100
    [6] => 0
    [7] => 100
    [8] => 50
    [9] => 100
    [10] => 0
    [11] => 100
    [12] => 0
    [13] => 100
    [14] => 0
    [15] => 100
    [16] => 0
    [17] => 100
    [18] => 0
    [19] => 100
    [20] => 0
    [21] => 100
)

I need to remove all 0's from this array, is this possible with a PHP array function

+1  A: 

You can just loop through the array and unset any items that are equal to 0

foreach($array as $array_key=>$array_item)
{
  if($array[$array_key] == 0)
  {
    unset($array[$array_key]);
  }
}
Jon Winstanley
+10  A: 

array_filter does that. If you don’t supply a callback function, it filters all values out that equal false (boolean conversion).

Gumbo
Nice solution. I suppose my answer remains useful for anyone who has this issue but the value to remove is non-zero.
Jon Winstanley
A callback can be used with array_filter() for when the filtering needs to be customised.
salathe