What is the difference between empty and array_filter in PHP when judging if the array is empty?

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

  • 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.