Home  >  Article  >  Backend Development  >  PHP removes null elements from arrays (array_filter)_PHP tutorial

PHP removes null elements from arrays (array_filter)_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:17:373559browse

PHP removes null elements from arrays (array_filter)

It’s embarrassing to say that in the past, when removing null values ​​from arrays, foreach or while were forced. Use these two A syntax structure to delete empty elements in an array, the simple code is as follows:

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

It turns out that this processing is not efficient if the array is too large. Because foreach copies the currently operated array, each foreach operation copies a variable. If there are too many foreach on the page, it will be a big waste.

When I was wandering around on the Internet, I saw someone prompting me to use array_filter, so I opened the manual and looked at it, and found that I had been guarding a treasure trove but didn’t know how to use it.

The function of the array_filter function is to use a callback function to filter the array. If there is no callback function, the default is to delete items with a false value in the array. Example below:

<?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
)

Suggestion: The two most important chapters in PHP should be array operations and string operations. You must be proficient in the functions in these two chapters. You can check the other ones when you use them.

Articles you may be interested in

  • php clears null elements in the array
  • php finds whether a value exists in the array (in_array(), array_search(), array_key_exists())
  • How to delete the first and last elements of an array in php
  • php pushes elements to the head of the array (usage of array_unshift)
  • PHP merge array + difference with array_merge
  • php gets the last element of the array
  • Two-dimensional array removes duplicate values ​​and array_unique function
  • PHP adds inverse in front of the quotation marks The reason for slashes and how to remove backslashes in PHP. Three ways to close php magic quotes

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/890694.htmlTechArticlePHP removes null value elements from arrays (array_filter) It’s embarrassing to say that in the past, it was the only way to remove null values ​​​​from arrays. It is forced to write foreach or while, use these two grammatical structures to delete the array...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn