Use array_filter to filter arrays to empty values ​​in php_PHP tutorial

WBOY
Release: 2016-07-20 11:03:18
Original
1022 people have browsed it

During our development process, what method would you think of when judging that the array is empty? The first thing that comes to mind should be the empty function, but it is wrong to directly use the empty function to determine if it is empty, because when the value is multi-dimensional, 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. Here is an example usage:

The

array_filter() function uses a callback function to filter the elements in the array. If the custom filter function returns true, the current value of the operated array will be included in the returned result array, and the result will be formed into a new array. If the original array is an associative array, the key names remain unchanged.

The code is as follows Copy code
 代码如下 复制代码


$array = array(
 
0 => '霜天部落',
 
1 => false,
 
2 => 1,
 
3 => null,
 
4 => '',
 
5 => 'http://www.hzhuti.com',
 
6 => '0'
 
);
 
print_r(array_filter($array));
 
?>

上面代码输出结果为:

Array
(
[0] => 霜天部落
[2] => 1
[5] => http://www.hzhuti.com
)


$array = array(

0 => 'Frost Sky 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 Sky Tribe
[2] => 1
[5] => http://www.hzhuti.com
)

This will exclude empty, null or false values
 代码如下 复制代码
function delEmpty($v)   
{  
if ($v==="" || $v==="php")   //当数组中存在空值和php值时,换回false,也就是去掉该数组中的空值和php值
    {  
    return false;  
    }  
return true;  
}  
$a=array(0=>"pig",1=>"Cat",2=>"",3=>"php");  
print_r(array_filter($a,"delEmpty")); 

We will further optimize the above

http://www.bkjia.com/PHPjc/445291.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/445291.html
TechArticle
During our development process, what method would you think of when judging that the array is empty? The first thing that comes to mind should be the empty function, but it is wrong to directly use the empty function to determine if it is empty, because when this...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!