Home  >  Article  >  Backend Development  >  PHP删除数组中的空值的函数array_filter

PHP删除数组中的空值的函数array_filter

WBOY
WBOYOriginal
2016-06-20 13:03:331293browse

以前在去掉数组的空值是都是强写foreach或者while的,利用这两个语法结构来删除数组中的空元素,简单代码如下:PHP代码

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

这样的效率并不高,因为:foreach是将当前操作的数组进行copy,每操作一下foreach,都是copy了一个变量,页面里面如果有太多的foreach,会是一个很大的消耗。

现在我发现了一个函数 array_filter()函数的功能是利用回调函数来对数组进行过滤,一直都以为用回调函数才能处理,却没有发现手册下面还有一句,如果没有回调函数,那么默认就是删除数组中值为false的项目。

例程:

PHP代码

<p><?php</p><p>$entry = array(0 => ‘scutephp.com’,1 => false,2 => -1,3 => null,4 => ”,5 =>1,6 => 0);</p><p>print_r(array_filter($entry));</p><p>?></p>

输出值为:

Array([0] => 'scutephp.com'[2] => -1[5]=>5)


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