Home  >  Article  >  Backend Development  >  How to remove empty array elements in php

How to remove empty array elements in php

王林
王林Original
2020-11-03 14:22:222471browse

php去除空的数组元素的方法:可以利用array_filter函数来删除数组中的空元素,如【array_filter($array)】。array_filter函数通过用回调函数来过滤数组中的元素。

How to remove empty array elements in php

函数介绍:

array_filter() 函数用回调函数过滤数组中的元素。

该函数把输入数组中的每个键值传给回调函数。如果回调函数返回 true,则把输入数组中的当前键值返回给结果数组。数组键名保持不变。

(推荐教程:php视频教程

代码实现:

 "abc", 'b' => "bcd",'c' =>"cde",'d' =>"def",'e'=>"");
    $b= array_filter($array);

    print_r($b);
?>

执行结果:

Array (
[a] => abc
[b] => bcd
[c] => cde
[d] => def
)

利用foreach或者while语法结构来删除数组中的空元素

代码实现:

注意:这样的效率并不高。也曾经试过先将$arr转为对象,然后利用对象的特性来删除。因为foreach是将当前操作的数组进行copy,每操作一下foreach,都是copy了一个变量,页面里面如果有太多的foreach,会是一个很大的消耗。

相关推荐:php培训

The above is the detailed content of How to remove empty array elements in php. For more information, please follow other related articles on the PHP Chinese website!

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