How to check if an array contains empty elements?

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

Let\'s make some examples:

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

What\'s

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题