How to delete null values ​​in an array in php?

青灯夜游
Release: 2023-03-02 20:06:02
Original
3430 people have browsed it

在PHP中,可以使用array_filter()函数来删除数组中的空值。array_filter()函数的功能是利用回调函数来对数组进行过滤,如果没有回调函数,那么默认就是删除数组中值为false的元素。

How to delete null values ​​in an array in php?

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

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

array_filter()函数中如果没有回调函数,那么默认就是删除数组中值为false的元素。

语法

array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )
Copy after login

How to delete null values ​​in an array in 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=>$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 delete null values ​​in an array 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