如何从PHP中的数组中删除空值和空值?

时间:2016-01-14 04:36:01

标签: php arrays

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

$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 ) 

任何建议都非常感谢。

3 个答案:

答案 0 :(得分:6)

试试这个:使用array_diff()函数比较两个(或更多)数组的值,并返回差异。删除null和“”。如果你需要删除一些更多的字段,那么在数组

中添加这些值
<?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

答案 1 :(得分:1)

尝试 array_filter ,将第二个参数作为用户定义的函数,如下所示:

createdb testingdb #(Again, type this on the shell prompt, not inside psql!)

psql testingdb
CREATE TABLE tbl1(a INT);
\q

答案 2 :(得分:0)

使用此代码,首先我更正了数组的索引,然后从数组中取消设置空值,然后再次更正数组索引:

$listValues = array("one", "two", "null","three","","four","null");
$listValues = array_values($listValues);
$temp = $listValues;

for($loop=0; $loop<count($listValues); $loop++){
    if($listValues[$loop] == "" || $listValues[$loop] == "null"){
        unset($temp[$loop]);
    }
}

$listValues = $temp;
$listValues = array_values($listValues);
echo "<pre>";
print_r($listValues);
echo "</pre>"; die;

但是,如果你想要相同的索引来获得这个输出:

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

然后在<pre>

之前不要使用它
$listValues = array_values($listValues);