50

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

Jon Winstanley
  • 23,010
  • 22
  • 73
  • 116
Elitmiar
  • 35,072
  • 73
  • 180
  • 229

7 Answers7

105

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

Gumbo
  • 643,351
  • 109
  • 780
  • 844
11

bit late, but copy & paste:

$array = array_filter($array, function($a) { return ($a !== 0); });
Slav
  • 576
  • 8
  • 28
8

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

foreach ($array as $array_key => $array_item) {
  if ($array[$array_key] === 0) {
    unset($array[$array_key]);
  }
}
Jon Winstanley
  • 23,010
  • 22
  • 73
  • 116
7

You can use this:

$result = array_diff($array, [0]);   
Amir Fo
  • 5,163
  • 1
  • 43
  • 51
4

First Method:

<?php
    $array = array(0,100,0,150,0,200);

    echo "<pre>";
    print_r($array);
    echo "</pre>";

    foreach($array as $array_item){
            if($array_item==0){
               unset($array_item);
        }
        echo"<pre>";
        print_r($array_item);
        echo"</pre>";
    }
?>

Second Method: Use array_diff function

  <?php
    $array = array(0,100,0,150,0,200);
    $remove = array(0);
    $result = array_diff($array, $remove);                          
    echo"<pre>";
    print_r($result);
    echo"</pre>";
  ?>
thecodedeveloper.com
  • 3,220
  • 5
  • 36
  • 67
4
$array = array_filter($array, function($a) { return ($a !== 0); });"

if you want to remove zero AND empty values, the right code is:

$array = array_filter($array, function($a) { return ($a !== 0 AND trim($a) != ''); });
krez
  • 45
  • 3
0

If you don't care about preserving key to data correlations, you can use this single line trick :

<?php
$a = array(0, 150, 0, 100, 0, 100, 0, 100);

$b = explode('][', trim(str_replace('[0]', '', '['.implode('][', $a).']'), '[]'));

print_r($b); // Array ([0] => 150 [1] => 100 [2] => 100 [3] => 100)