Home  >  Article  >  Backend Development  >  How to delete null values ​​in an array in php?

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

青灯夜游
青灯夜游Original
2020-07-21 16:53:113269browse

在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 ]] )

How to delete null values ​​in an array in 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的,利用这两个语法结构来删除数组中的空元素,简单代码如下:

$v){
if( !$v )
unset( $arr[$k] );
}
>

而且自我感觉还挺不错,只是这样的效率并不高也曾经试过,先将$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!

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