Ask a weak question, for example, what is the difference between the following code when determining whether the array is empty? The {code...} is weak. For example, what is the difference between the following code and determining whether the array is null?
$arr = array('a'=>'');if(array_filter($arr)) echo 'succ';else echo 'failed';if(empty($arr)) echo 'succ';else echo 'failed';
Reply content:
Ask a weak question, for example, what is the difference between the following code when determining whether the array is empty?
$arr = array('a'=>'');if(array_filter($arr)) echo 'succ';else echo 'failed';if(empty($arr)) echo 'succ';else echo 'failed';
This code will print two failed messages.
First, we will discuss the problem of converting an array to a Boolean value (true/false.
The manual says: the array that does not contain any element is false, and the rest are true.
Http://www.php.net/manual/zh/language.types.boolean.php#language.types.boolean.casting
Then let's look at the behavior of these two functions.
Array_filter filters parameters and returns a new array. By default, all elements whose values are false are excluded.
The empty string is converted to false, so the only element in $ arr is deleted and an empty array is returned. The empty array is converted to false, and the first failed is printed.
(As mentioned in the manual) the action of empty is typically equivalent to converting a parameter to a Boolean value and taking the inverse, that isempty($x)
Equivalent!$x
.
$ Arr is not an empty array, so it is converted to true, and the inverse value is false, so the second failed is printed.