How to determine if an array has any elements or not?

后端 未结 8 2064
青春惊慌失措
青春惊慌失措 2020-12-06 09:31

How do I find if an array has one or more elements?

I need to execute a block of code where the size of the array is greater than zero.

if ($result &         


        
8条回答
  •  星月不相逢
    2020-12-06 09:56

    Pro Tip:

    If you are sure that:

    1. the variable exists (isset) AND
    2. the variable type is an array (is_array) ...might be true of all is_iterables, but I haven't researched that extension of the question scope.

    Then you don't need to call any functions. An array with one or more elements has a boolean value of true. An array with no elements has a boolean value of false.

    Code: (Demo)

    var_export((bool)[]);
    echo "\n";
    var_export((bool)['not empty']);
    echo "\n";
    var_export((bool)[0]);
    echo "\n";
    var_export((bool)[null]);
    echo "\n";
    var_export((bool)[false]);
    echo "\n";
    
    $noElements = [];
    if ($noElements) {
        echo 'not empty';
    } else {
        echo 'empty';
    }
    

    Output:

    false
    true
    true
    true
    true
    empty    
    

提交回复
热议问题