Remove null values โ€‹โ€‹from PHP array

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 from this array, is this possible using the PHP array function

+37
source share
8 answers

array_filter does this. If you do not provide a callback function, it filters all values โ€‹โ€‹equal to false ( logical conversion ).

+85
source

You can simply iterate over the array and discard any elements that are exactly 0

 foreach ($array as $array_key => $array_item) { if ($array[$array_key] === 0) { unset($array[$array_key]); } } 
+8
source

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

  <?php $array = array(0,100,0,150,0,200); $remove = array(0); $result = array_diff($array, $remove); echo"<pre>"; print_r($result); echo"</pre>"; ?> 
+5
source

bit later, but copy and paste:

 $array = array_filter($array, function($a) { return ($a !== 0); }); 
+4
source

If you don't care about saving the key for data correlation, 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) 
+1
source

You can use this:

 $result = array_diff($array, [0]); 
+1
source
 $array = array_filter($array, function($a) { return ($a !== 0); });" 

if you want to remove zero and empty values, the correct code is:

 $array = array_filter($array, function($a) { return ($a !== 0 AND trim($a) != ''); }); 
0
source

It is also an effective solution to remove unwanted value.

  <?php $array = array(0,100,0,150,0,200); foreach($array as $a){ if (false !== $key = array_search("0", $array)){ unset($array[$key]); } } print_r($array); ?> 
-1
source

Source: https://habr.com/ru/post/910002/


All Articles