php 如何从数组中删除空值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20676771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove null values from an array?
提问by user3056158
I have an array
我有一个数组
Array ( [0] => 0 [1] => [2] => 3 [3] => )
数组( [0] => 0 [1] => [2] => 3 [3] => )
i want to remove null values from this and the result should be like this
我想从中删除空值,结果应该是这样的
Array ( [0] => 0 [1] => 3) i don't want to remove 0 value from array.
数组 ( [0] => 0 [1] => 3) 我不想从数组中删除 0 值。
回答by floww
this will do the trick:
这将解决问题:
array_filter($arr, static function($var){return $var !== null;} );
Code Example: http://3v4l.org/icEDa
代码示例:http: //3v4l.org/icEDa
for older versions (php<5.3):
对于旧版本(php<5.3):
function is_not_null ($var) { return !is_null($var); }
$filtered = array_filter($arr, 'is_not_null');
Code Example: http://3v4l.org/CKrYO
代码示例:http: //3v4l.org/CKrYO
回答by Mr. Alien
You can use array_filter()which will get rid of the null empty values from the array
您可以使用array_filter()which 将摆脱数组中的 null 空值
print_r(array_filter($arr, 'strlen'));
回答by casraf
You can just loop through it.
你可以循环遍历它。
<?php
foreach ($array as $i=>$row) {
if ($row === null)
unset($array[$i]);
}
If you want to reindex the array to remove gaps between keys, you can just use a new array:
如果你想重新索引数组以消除键之间的间隙,你可以使用一个新数组:
<?php
$array2 = array();
foreach ($array as $row) {
if ($row !== null)
$array2[] = $row;
}
$array = $array2;
回答by Edgar Klerks
You are in a world of trouble now, because it is not too easy to distinguish null from 0 from false from "" from 0.0. But don't worry, it is solvable:
你现在处于一个麻烦的世界,因为区分 null 和 0 与 false 与 "" 和 0.0 并不是一件容易的事。不过别担心,它是可以解决的:
$result = array_filter( $array, 'strlen' );
Which is horrible by itself, but seems to work.
这本身就很可怕,但似乎有效。
EDIT:
编辑:
This is bad advice, because the trick leans on a strange corner case:
这是一个糟糕的建议,因为这个技巧依赖于一个奇怪的角落案例:
- strlen(0) will be strlen("0") -> 1, thus true
- strlen(NULL) will be strlen("")->0, thus false
- strlen("") will be strlen(("")->0, thus false etc.
- strlen(0) 将是 strlen("0") -> 1,因此为真
- strlen(NULL) 将是 strlen("")->0,因此为 false
- strlen("") 将是 strlen(("")->0,因此为 false 等。
The way you should do it is something like this:
你应该这样做的方式是这样的:
$my_array = array(2, "a", null, 2.5, NULL, 0, "", 8);
function is_notnull($v) {
return !is_null($v);
}
print_r(array_filter($my_array, "is_notnull"));
This is well readable.
这很好读。
回答by harry
<?php
$arr = array( 0 => 0, 1=>null, 2=>3, 3=>null);
foreach ($arr as $key=>$val) {
if ($val === null)
unset($arr[$key]);
}
$new_arr = array_values($arr);
print_r($new_arr);
?>
Out put:
输出:
Array
(
[0] => 0
[1] => 3
)
回答by Let me see
simply
简单地
$keys=array_keys($yourArray,NULL);
if(!empty($keys))
{
foreach($keys as $key)
{
unset($yourArray[$key]);
}
}
var_dump($yourarray);

