什么用于删除数组的空值最少的时间?

时间:2017-10-10 15:40:42

标签: php arrays performance

我想删除数组中的值。您提供的内容将用作优化选项,最少的时间损失。顺便说一下,不能删除带空格的值。例如,我使用array_filter()来执行此任务:

$array = array(null, " ", false, "apple", "", "- ", "   .");

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

/* Output */

Array
(
    [0] => 
    [1] =>  
    [2] => 
    [3] => apple
    [4] => 
    [5] => - 
    [6] =>    .
)


$array = array_filter($array);

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

/* Output */

Array
(
    [1] =>  
    [3] => apple
    [5] => - 
    [6] =>    .
)

你建议用什么来从数组中删除一个空值:一个循环或函数array_filter()还是别的什么?

2 个答案:

答案 0 :(得分:0)

两种方法array_filterarray_walk

的示例

array_walk示例

$array = [null, " ", false, "apple", "", "- ", "   ."];

$start = microtime(true);
array_walk($array, function (&$value, $key) use (&$array) {
    if (empty(trim($value)) && !is_null($value))
    {
        unset($array[$key]);
    }
});
$end = microtime(true);

var_dump([$array, $end-$start]);

将输出

array (size=2)
  0 => 
    array (size=4)
      0 => null
      3 => string 'apple' (length=5)
      5 => string '- ' (length=2)
      6 => string '   .' (length=4)
  1 => float 2.0980834960938E-5

array_filter示例

$array = [null, " ", false, "apple", "", "- ", "   ."];

var_dump($array);

$start = microtime(true);
$array = array_filter($array, function ($entry) {
    return (!empty(trim($entry)) || is_null($entry));
});
$end = microtime(true);

var_dump([$array, $end-$start]);

将输出

array (size=2)
  0 => 
    array (size=4)
      0 => null
      3 => string 'apple' (length=5)
      5 => string '- ' (length=2)
      6 => string '   .' (length=4)
  1 => float 1.6927719116211E-5

结论:array_filter更好!

答案 1 :(得分:0)

array_keys应该更快:

$array = array(...);

$keys = array_keys($array,"");

foreach ($keys as $k){
    unset($array[$k]);
}