check if an array have one or more empty values

后端 未结 5 2249
无人共我
无人共我 2021-02-19 11:34

I have the array $var, and I\'d like to return FALSE if one or more element in the array are empty (I mean, the string are \"\").

I think that array_filter()

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-19 12:06

    Or explicitly, as suggested by @Ancide:

    $var = array("lorem", "ipsum", "dolor");
    $emptyVar = array("lorem", "", "dolor");
    
    function has_empty($array) {
        foreach ($array as $value) {
            if ($value == "")
                return true;
        }
        return false;
    }
    
    echo '$var has ' . (has_empty($var) ? 'empty values' : 'no empty values');
    echo '
    '; echo '$emptyVar has ' . (has_empty($emptyVar) ? 'empty values' : 'no empty values');

    EDIT:

    I wasn't sure at first if array_search() stops at first occurrence. After verifying PHP's source it seems that array_search() approach should be faster (and shorter). Thus @Wh1T3h4Ck5's version would be preferable, I suppose.

提交回复
热议问题