删除数组中的空值元素

9
Array
    (
      [0] => 0   //value is int 0 which isn;t empty value
      [1] =>     //this is empty value
      [2] =>     //this is empty value
    )

我想将上面的数组转换为以下形式,有谁能帮我吗?
非常感谢。
Array
    (
      [0] => 0
    )

7
那些空值是什么?它们是false、NULL、空字符串还是其他的东西? 那么数字0呢?它是整数0还是字符串“0”? 使用var_dump()在数组上确定值的类型。 - BoltClock
5个回答

20

您可以使用array_filter函数来移除空值(null、false、''和0):

array_filter($array);

如果您不想从数组中删除0,请参阅@Sabari的答案:

array_filter($array,'strlen');

3
不知道第二个参数是可选的,这很好。 - Gajus
@Zulkhaery Basrul,array_filter会认为值0是空值,因此最终结果是一个空数组,这不是我想要的。 - Acubi
从PHP 8.1开始,strlen函数现在会发出一个弃用错误:"strlen(): Passing null to parameter #1 ($string) of type string is deprecated"。 - Brad Kent

5

您可以使用:

仅删除NULL值:

$new_array_without_nulls = array_filter($array_with_nulls, 'strlen');

删除假值:

$new_array_without_nulls = array_filter($array_with_nulls);

希望这可以帮助您 :)

从PHP 8.1开始,strlen函数现在会发出一个弃用错误:"strlen(): Passing null to parameter #1 ($string) of type string is deprecated"。 - Brad Kent
此外... strlen 回调函数还会删除空字符串和 false 值(除了 null)。 - Brad Kent

1
array_filter($array, function($var) {
    //because you didn't define what is the empty value, I leave it to you
    return !is_empty($var);
});

0

这是 array_filter 的典型应用案例。您首先需要定义一个函数,如果值应该被保留,则返回TRUE,如果应该被删除,则返回FALSE

function preserve($value)
{
    if ($value === 0) return TRUE;

    return FALSE;
}

$array = array_filter($array, 'preserve');

然后在回调函数中(这里是preserve),您指定什么是空的,什么不是。由于您在问题中没有明确说明,因此需要自行完成。


0

快速查找数字,包括零(0)

    var_dump(  
            array_filter( array('0',0,1,2,3,'text') , 'is_numeric'  )
        );
/* 
print :
array (size=5)
  0 => string '0' (length=1)
  1 => int 0
  2 => int 1
  3 => int 2
  4 => int 3

*/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接