Php array_filter without saving key

if I filter the array with array_filter to exclude null values, the keys will be saved and this will create β€œholes” in the array. For example:

The filtered version of [0] => 'foo' [1] => null [2] => 'bar' is [0] => 'foo' [2] => 'bar' 

How can i get instead

 [0] => 'foo' [1] => 'bar' 

?

+38
arrays php
Apr 16 '10 at 12:50
source share
2 answers

You can use array_values after filtering to get the values.

+75
Apr 16 '10 at 12:51 on
source share

Using this input:

 $array=['foo',NULL,'bar',0,false,null,'0','']; 

There are several ways to do this. Demo

It is slightly off topic to raise the default greedy behavior of array_filter , but if you are looking for this page, this is probably important information related to your project / task:

 var_export(array_values(array_filter($array))); // NOT GOOD!!!!! 

Invalid output:

 array ( 0 => 'foo', 1 => 'bar', ) 



Now about how this will work:

Method # 1 : ( array_values() , array_filter() with / !is_null() )

 var_export(array_values(array_filter($array,function($v){return !is_null($v);}))); // good 

Method # 2 : ( foreach() , an automatically indexed array !==null )

 foreach($array as $v){ if($v!==null){$result[]=$v;} } var_export($result); // good 

Method # 3 : ( array_walk() , auto-indexing array !is_null() )

 array_walk($array,function($v)use(&$filtered){if(!is_null($v)){$filtered[]=$v;}}); var_export($filtered); // good 

All three methods provide the following "zero" output:

 array ( 0 => 'foo', 1 => 'bar', 2 => 0, 3 => false, 4 => '0', 5 => '', ) 



Starting with PHP7.4, you can even β€œrepack” as follows: (numeric keys are required for the splat operator)

Code: ( Demo )

 $array = ['foo', NULL, 'bar', 0, false, null, '0', '']; $array = [...array_filter($array)]; var_export($array); 

Exit:

 array ( 0 => 'foo', 1 => 'bar', ) 

... but as it turns out, repacking with the splat operator is much less efficient than calling array_values() .

+3
Apr 27 '17 at 11:54 on
source share



All Articles