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

后端 未结 9 2217
一生所求
一生所求 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:52

    array_filter should work fine if you use the identical comparison operator.

    here's an example

    $values = [NULL, FALSE, '', 0, 1];
    
    function myFilter($var){
      return ($var !== NULL && $var !== FALSE && $var !== '');
    }
    
    $res = array_filter($values, 'myFilter');
    

    Or if you don't want to define a filtering function, you can also use an anonymous function (closure):

    $res = array_filter($values, function($value) {
        return ($value !== null && $value !== false && $value !== ''); 
    });
    

    If you just need the numeric values you can use is_numeric as your callback: example

    $res = array_filter($values, 'is_numeric');
    
    0 讨论(0)
  • 2020-12-09 02:53

    From http://php.net/manual/en/function.array-filter.php#111091 :

    If you want to remove NULL, FALSE and Empty Strings, but leave values of 0, you can use strlen as the callback function:

    array_filter($array, 'strlen');
    
    0 讨论(0)
  • 2020-12-09 02:53

    Alternatively you can use array_filter with the 'strlen' parameter:

    // removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values
    $result = array_filter($array, 'strlen');
    

    https://www.php.net/manual/en/function.array-filter.php#111091

    0 讨论(0)
提交回复
热议问题