Home > php教程 > php手册 > body text

php中利用array_filter过滤数组为空值

WBOY
Release: 2016-06-13 11:19:42
Original
1352 people have browsed it

在我们开发过程中,判断数组为空时你会想到什么方法呢?首先想到的应该是empty函数,不过直接用empty函数判断为空是不对的,因为当这个值是多维数的时候,empty结果是有值的。  

其实我们可以利用array_filter函数轻松去掉多维空值,而数组的下标没有改变,下面是举例用法:

array_filter() 函数用回调函数过滤数组中的元素,如果自定义过滤函数返回 true,则被操作的数组的当前值就会被包含在返回的结果数组中, 并将结果组成一个新的数组。如果原数组是一个关联数组,键名保持不变。

 代码如下 复制代码


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

这样就把为空或者null或者false的值排除掉

上面我们再进行优化

 

 代码如下 复制代码
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")); 

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 Recommendations
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!