check if an array have one or more empty values

后端 未结 5 2246
无人共我
无人共我 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 '<br>';
    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.

    0 讨论(0)
  • 2021-02-19 12:09

    If you really want to check if one or more empty strings exists, it's simple. You can do,

    in_array('', $var, true);
    

    It returns true if empty string('') exists in at-least any one of the array values, false otherwise. You can refer this similar question too, how to check if an array has value that === null without looping?

    0 讨论(0)
  • 2021-02-19 12:22

    If you want to have a function which checks if a item in the array is false you could write your own function which does:

    • Iterates through the array
    • For each cycle check if current item value is ""
    • If the value is not "" run next cycle
    • If the value is "" break the loop by return False

    The array_filter takes a array and a function, then iterates through the array and sends in each item in the specified function. If the function returns true the the item is kept in the array and if the function returns false the item is taken out of the array.

    You see the difference, right?

    0 讨论(0)
  • 2021-02-19 12:25

    function emptyElementExists()

    function emptyElementExists($arr) {
      return array_search("", $arr) !== false;
      }
    

    Example:

    $var = array( "text1", "", "text3" );
    var_dump( emptyElementExists($var) );
    

    Output:

    bool(true)

    Reference

    • array_search()
    0 讨论(0)
  • 2021-02-19 12:25
    if (array_search('', $var)!==false) return FALSE;
    
    0 讨论(0)
提交回复
热议问题