使用array_map php查找数组中的所有负数

时间:2015-08-20 04:59:12

标签: php arrays callback array-map

我有这个测试数组

$test = array(-10,20,40,-30,50,-60);

我希望输出为

$out = array (-10, -30, -60);

这是我的解决方案:

$temp = array();

function neg($x)
{
    if ($x <0) 
    {
        $temp[] = $x; 
        return $x;
    }
}
$negative = array_map("neg", $test);

当我打印$negative时,我得到了我想要的东西但是有些条目为空。我可以在回调函数中做些什么来不记录空条目吗?

Array
(
    [0] => -10
    [1] => 
    [2] => 
    [3] => -30
    [4] => 
    [5] => -60
)
1

当我打印$temp数组时,我以为我会得到答案,但它打印出一个空数组。我不明白为什么,我清除了在我的回调函数中将$x添加到$temp[]数组。有什么想法吗?

print_r($temp);
// outputs
Array
(
)
1

1 个答案:

答案 0 :(得分:1)

当条件满足时,

array_map将返回value,如果条件失败,则返回NULL。在这种情况下,您可以使用array_filter

$test = array(-10,20,40,-30,50,-60);

$neg = array_filter($test, function($x) {
    return $x < 0;
});

<强>输出

array(3) {
  [0]=>
  int(-10)
  [3]=>
  int(-30)
  [5]=>
  int(-60)
}

如果您继续使用array_map,那么我建议在完成后应用array_filter -

$negative = array_map("neg", $test);
$negative = array_filter($negative);

输出结果相同。