How to remove empty array elements in php

王林
Release: 2023-03-07 06:48:01
Original
2640 people have browsed it

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

How to remove empty array elements in php

函数介绍:

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

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

(推荐教程:php视频教程

代码实现:

<?php
    $array = array(&#39;a&#39; => "abc", &#39;b&#39; => "bcd",&#39;c&#39; =>"cde",&#39;d&#39; =>"def",&#39;e&#39;=>"");
    $b= array_filter($array);

    print_r($b);
?>
Copy after login

执行结果:

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

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

代码实现:

<?php
foreach( $arr as $k=&gt;$v){
if( !$v )
unset( $arr[$k] );
}
>
Copy after login

注意:这样的效率并不高。也曾经试过先将$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!

Related labels:
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