In the PHP development process, it is often necessary to determine whether an array is empty. There are two situations in determining whether an array is empty. One is that the array has no elements, and the other is that the variable does not exist or the value is null.
The following are two ways to determine the empty array:
PHP provides an empty() method, which can be easily and quickly determined Whether the array is empty.
It should be noted here that the empty() function has a special judgment on arrays. array(), array(0) and false will all be judged as empty.
The sample code is as follows:
$arr = array(); if(empty($arr)){ echo "数组为空"; }
The above code creates an empty array, uses the empty() function to determine whether the array is empty, and finally outputs "array is empty".
In addition, we can also use the count() function to determine whether an array is empty. If the number of elements in an array is 0, then we consider it an empty array.
The sample code is as follows:
$arr = array(); if(count($arr) === 0){ echo "数组为空"; }
The above code creates an empty array, uses the count() function to determine whether the array is empty, and finally outputs "array is empty".
At the same time, the count() function can also determine whether a variable is null. If it is null, it returns 0. You can determine whether the variable is null by determining whether the return value of count() is equal to 0.
$var = null; if(count($var) === 0){ echo "变量为null"; }
The above code creates a null variable, uses the count() function to determine whether the variable is null, and finally outputs "the variable is null".
To sum up, the above two methods can be used to determine whether an array is empty, and you can choose to use it according to the actual situation.
The above is the detailed content of How to determine an empty array in php (two methods). For more information, please follow other related articles on the PHP Chinese website!