Home  >  Article  >  php教程  >  php清除数组中的空值元素

php清除数组中的空值元素

WBOY
WBOYOriginal
2016-06-21 08:49:121507browse

对于一个一维的php数组,如何清除其中值为空的元素呢?直接的办法是foreach循环一下,一个个判断排除。不过这个方法还是略显复杂,下面分享一下今天看到的一个方法,很简洁也是头一次看到这种写法的,记录一下。

假设存在如下一个一维数组:

$array=array(0=>'Alixixi',1=>'',2=>'com',3=>'');

清除该数组中的空元素可以这么写:

$array=array_filter($array,create_function('$v','return !empty($v);'));
print_r($array);
//输出结果:Array ( [0] => Alixixi [2] => com );

简要分析一下以上代码中两个比较重要的函数:

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

string create_function(string $args,string $code) 创建一个匿名函数。



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