PHP removes null-valued elements from arrays (array

Source: Internet
Author: User
Tags foreach array arrays copy empty

Ashamed to say, before the null values of the array are all strong write foreach or while, using these two syntactic structures to delete the empty elements in the array, simple code is as follows:

<?php   
foreach ($arr as $k => $v) {
    if (! $v) unset ($arr [$k]);   
}

It turns out that if the array is too large, the efficiency of this process is not high. Because foreach is the current operation of the array copy, each operation of foreach, is a copy of a variable, the page if there are too many foreach, will be a great consumption.

Wandering on the Internet, see people have hints with array_filter, so open the manual looked, found himself has been guarding a baoshan but do not know how to use.

The function of the Array_filter function is to use the callback function to filter the array, and if there is no callback function, the default is to delete the item whose value is False. The following example:

<?php
$entry = Array (   
	0 => ' foo ',   
	1 => false,   
	2 =>-1,   
	3 => NULL,   
	4 => '
);
Print_r (Array_filter ($entry));

The output value is:

Array
(
[0] => foo
[2] =>-1
)

Recommendation: PHP is the most important two chapters should be array operation and string operation, the two chapters inside the function must be skilled, the other is used when the time to check it.

Articles that you may be interested in

    • How do I remove an element from a PHP array (unset,array_splice)?
    • PHP clears the empty value element in the array
    • PHP finds whether a value exists in the array (In_array (), Array_search (), array_key_exists ())
    • How PHP deletes the first and last elements of an array
    • The difference between the PHP merge array + and the Array_merge
    • PHP presses the element to the array header (Array_unshift usage)
    • PHP gets the last element of the array
    • Two-dimensional array removal of duplicate values and Array_unique functions


Related Article

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.