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)));
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);})));
Method # 2 : ( foreach() , an automatically indexed array !==null )
foreach($array as $v){ if($v!==null){$result[]=$v;} } var_export($result);
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);
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() .