What is the difference between empty and array_filter in php when determining whether the array is empty?

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.