How to check if array is empty - true or false

2020-03-15 01:11发布

问题:

I have a question, how do I put a condition for a function that returns true or false, if I am sure that the array is empty, but isset() passed it.

$arr = array();

if (isset($arr)) {
    return true;
} else {
    return false;
}

In this form returns bool(true) and var_dump shows array (0) {}.

回答1:

If it's an array, you can just use if or just the logical expression. An empty array evaluates to FALSE, any other array to TRUE (Demo):

$arr = array();

echo "The array is ", $arr ? 'full' : 'empty', ".\n";

The PHP manually nicely lists what is false and not.



回答2:

Use PHP's empty() function. It returns true if there are no elements in the array.

http://php.net/manual/en/function.empty.php



回答3:

Use empty() to check for empty arrays.

if (empty($arr)) {
  // it's empty
} else {
  // it's not empty
}


回答4:

You can also check to see how many elements are in the array via the count function:

$arr = array();

if (count($arr) == 0) {
  echo "The array is empty!\n";
} else {
  echo "The array is not empty!  It has " . count($arr) . " elements!\n";
}


回答5:

use the empty property as

if (!empty($arr)) {
    //do what u want if its not empty
} else {
    //do what if its empty
}


标签: php arrays