How to check if an array contains empty elements?

后端 未结 6 2008
生来不讨喜
生来不讨喜 2020-12-10 02:31

Let\'s make some examples:

array(\"Paul\", \"\", \"Daniel\") // false
array(\"Paul\", \"Daniel\") // true
array(\"\",\"\") // false

What\'s

相关标签:
6条回答
  • 2020-12-10 02:33

    Try using in_array:

    return !in_array("", array("Paul", "", "Daniel")); //returns false
    
    0 讨论(0)
  • 2020-12-10 02:36

    The answer depends on how you define "empty"

    $contains_empty = count($array) != count(array_filter($array));
    

    this checks for empty elements in the boolean sense. To check for empty strings or equivalents

    $contains_empty = count($array) != count(array_filter($array, "strlen"));
    

    To check for empty strings only (note the third parameter):

    $contains_empty = in_array("", $array, true);
    
    0 讨论(0)
  • 2020-12-10 02:45
    $array = array("Paul", "", "Daniel") 
    if( $array  != array_filter( $array ) ) 
    return FALSE;
    
    0 讨论(0)
  • 2020-12-10 02:45
    function has_empty(array $array)
    {
        return count($array) != count(array_diff($array, array('', null, array())));
    }
    
    0 讨论(0)
  • 2020-12-10 02:54
    function testEmpty($array) {
      foreach ($array as $element) {
        if ($element === '')
          return false;
      }
      return true;
    }
    

    Please check out the comments down below for more information.

    0 讨论(0)
  • 2020-12-10 02:57

    Since I do enjoy me some fancy anonymous functions here is my take on it. Not sure about performance, but here it is:

    $filter = array_filter(
            ["Paul", "", "Daniel"],
            static function ($value) {
                return empty($value); // can substitute for $value === '' or another check
            }
        );
    
    return (bool) count($filter);
    

    Logically explained. If anonymous returns true, it means that it found an empty value. Which means the filter array will contain only empty values at the end (if it has any).

    That's why the return checks if the filter array has values using count function.

    The (bool) type cast is equivalent to return count($filter) === 0.

    May you all find the happiness you seek.

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