Remove NULL, FALSE, and '' - but not 0 - from a PHP array

后端 未结 9 2377
一生所求
一生所求 2020-12-09 02:15

I want to remove NULL, FALSE and \'\' values .

I used array_filter but it removes the 0\' s also.

9条回答
  •  醉话见心
    2020-12-09 02:41

    function my_filter($var)
    {
        // returns values that are neither false nor null (but can be 0)
        return ($var !== false && $var !== null && $var !== '');
    }
    
    $entry = array(
                 0 => 'foo',
                 1 => false,
                 2 => -1,
                 3 => null,
                 4 => '',
                 5 => 0
              );
    
    print_r(array_filter($entry, 'my_filter'));
    

    Outputs:

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

提交回复
热议问题