Remove zero values from a PHP array

Viewed 48383

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

7 Answers

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]);
  }
}

You can use this:

$result = array_diff($array, [0]);   
$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) != ''); });
Related