How to remove false, null and Zero value from an Array in PHP

There is no need for this kind of operation. Simply use array_filter(), which conveniently handles all this job for you:

Below code will simply remove all the false, null and zero value from an array.

If you want to remove false and null but keeping zero value then you can use the standard php's 'strlen' function as the callback function:

And if you want to remove false and null values by keeping empty string value ('') as it is, you can make your own callback function.
<?php

$entry = array(
               0 => 'foo',
               1 => false,
               2 => -1,
               3 => null,
               4 => '',
               5 => 0
         );

function myFilter($value){
         return (is_numeric($value) || is_string($value) || (empty($value) === false));
}

echo "<pre>";
print_r(array_filter( $entry ));
echo "</pre>";

echo "<pre>";
print_r(array_filter( $entry, 'strlen' ));
echo "</pre>";

echo "<pre>";
print_r(array_filter( $entry, 'myFilter' ));
echo "</pre>";

?>


Output:

Array
(
    [0] => foo
    [2] => -1
)


Array
(
    [0] => foo
    [2] => -1
    [5] => 0
)


Array
(
    [0] => foo
    [2] => -1
    [4] => 
    [5] => 0
)

Post a Comment

0 Comments