如何从PHP数组中删除空值和空值? [英] How to remove empty and null values from an array in php?

查看:116
本文介绍了如何从PHP数组中删除空值和空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 $ listValues 数组中删除空值和空值。
在这里,我使用 array_filter 删除了空值。
示例代码:

I want to remove the empty and null values from $listValues array. Here I am removed the empty values using array_filter. Sample Code:

$listValues = array("one", "two", "null","three","","four","null");
$resultValues = array_filter($listValues);

echo "<pre>";
print_r($resultValues);
echo "</pre>";

结果:

Array ( [0] => one [1] => two [2] => null [3] => three [5] => four [6] => null ) 

但是我想要

Array ( [0] => one [1] => two [3] => three [5] => four ) 

任何建议都非常感谢。

推荐答案

尝试一下:使用array_diff()函数比较两个(或更多)数组的值,并返回差值。删除null和。如果您需要删除更多字段,则在数组中添加该值

try this : use array_diff() function compares the values of two (or more) arrays, and returns the differences. to remove null and "" . if you need to remove some more field then add that values inside the array

<?php
$listValues = array("one", "two", "null","three","","four","null");
echo "<pre>";
$a=array_values(array_diff($listValues,array("null","")));
print_r($a);
echo "</pre>";
?>

输出:

Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => four
)

请参考
http://www.w3schools.com/php/func_array_diff.asp

这篇关于如何从PHP数组中删除空值和空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆