Weak weak Ask a question, such as the following code, in determining whether the array is empty, what is the difference?
$arr = array('a'=>'');if(array_filter($arr)) echo 'succ';else echo 'failed';if(empty($arr)) echo 'succ';else echo 'failed';
Reply content:
Weak weak Ask a question, such as the following code, in determining whether the array is empty, what is the difference?
$arr = array('a'=>'');if(array_filter($arr)) echo 'succ';else echo 'failed';if(empty($arr)) echo 'succ';else echo 'failed';
This piece of code prints two failed.
First we will discuss the problem of converting arrays to Boolean values (True/false).
The manual says: "The array with no elements is false and the rest is true."
Http://www.php.net/manual/zh/language.types.boolean.php#language.types.boolean.casting
We then look at the behavior of these two functions.
Array_filter Filters The parameters, returns a new array, and by default rejects all elements that have a value of false.
The empty string is converted to false, so the only element in $arr is deleted, an empty array is returned, the empty array is converted to false, and the first failed is printed.
The behavior of empty is, in most cases, equivalent to converting a parameter to a Boolean value and taking the inverse, which is empty($x)
equivalent to !$x
.
The $arr is not an empty array, so it is converted to true and reversed to false, so a second failed is printed.