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

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

    array_filter doesn't work because, by default, it removes anything that is equivalent to FALSE, and PHP considers 0 to be equivalent to false. The PHP manual has this to say on the subject:

    When converting to boolean, the following values are considered FALSE:

    • the boolean FALSE itself
    • the integer 0 (zero)
    • the float 0.0 (zero)
    • the empty string, and the string "0"
    • an array with zero elements
    • an object with zero member variables (PHP 4 only)
    • the special type NULL (including unset variables)
    • SimpleXML objects created from empty tags

    Every other value is considered TRUE (including any resource).

    You can pass a second parameter to array_filter with a callback to a function you write yourself, which tells array_filter whether or not to remove the item.

    Assuming you want to remove all FALSE-equivalent values except zeroes, this is an easy function to write:

    function RemoveFalseButNotZero($value) {
      return ($value || is_numeric($value));
    }
    

    Then you just overwrite the original array with the filtered array:

    $array = array_filter($array, "RemoveFalseButNotZero");
    

提交回复
热议问题