How to check if array is empty - true or false
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;
} e开发者_如何学运维lse {
return false;
}
In this form returns bool(true)
and var_dump
shows array (0) {}
.
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";
Sometimes it is suggested instead of just if
'ing the array variable like:
if (!$array) {
// empty
}
to write out:
if (empty($array)) {
// empty
}
for readability reasons. Compare empty(php)
language construct.
The PHP manually nicely lists what is false and not.
Use PHP's empty()
function. It returns true
if there are no elements in the array.
http://php.net/manual/en/function.empty.php
Use empty()
to check for empty arrays.
if (empty($arr)) {
// it's empty
} else {
// it's not empty
}
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";
}
use the empty property as
if (!empty($arr)) {
//do what u want if its not empty
} else {
//do what if its empty
}
精彩评论