Using array_filter in php to filter arrays with null values _ PHP Tutorial

Source: Internet
Author: User
In php, array_filter is used to filter the array to null values. What methods do you think of when we judge that the array is empty during the development process? The first thought should be the empty function, but it is wrong to use the empty function to judge whether it is null, because during our development, what method do you think of when judging that the array is empty? The first thought should be the empty function, but it is wrong to use the empty function to judge whether it is null, because when the value is a multi-dimensional number, the empty result has a value.

In fact, we can use the array_filter function to easily remove multi-dimensional null values without changing the subscript of the array. The following is an example:

The array_filter () function uses the callback function to filter elements in the array. if the custom filter function returns true, the current value of the operated array is included in the returned result array, and form a new array of results. If the original array is an associated array, the key name remains unchanged.

The code is as follows:


$ Array = array (

0 => 'Frost tribe ',

1 => false,

2 => 1,

3 => null,

4 => '',

5 => 'http: // www.hzhuti.com ',

6 => '0'

);

Print_r (array_filter ($ array ));

?>

The output result of the above code is:

Array
(
[0] => Frost tribe
[2] => 1
Http://www.hzhuti.com
)

In this way, the values of null or false are excluded.

We will optimize the above.

The code is as follows:
Function delEmpty ($ v)
{
If ($ v = "" | $ v = "php") // returns false if the array contains Null Values and php values, that is, remove the null and php values in the array.
{
Return false;
}
Return true;
}
$ A = array (0 => "pig", 1 => "Cat", 2 => "", 3 => "php ");
Print_r (array_filter ($ a, "delEmpty "));

Why? The first thought should be the empty function, but it is wrong to directly use the empty function to judge whether it is null, because when this...

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.