PHP从数组两侧删除空项 [英] PHP remove empty items from sides of an array

查看:82
本文介绍了PHP从数组两侧删除空项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组:

Array 
(
[0] => 
[1] => 
[2] => apple
[3] => 
[4] => orange
[5] => strawberry
[6] => 
)

如何从开头和结尾删除空白项,而不是从内部删除空白项?最终的数组应如下所示:

How can I remove the empty items from the beginning and the end, but not from the inside? The final array should look like this:

Array 
(
[0] => apple
[1] => 
[2] => orange
[3] => strawberry
)

推荐答案

这是一种便捷的方法:

while (reset($array) == '') array_shift($array);
while (end($array) == '') array_pop($array);

实际操作中 .

强制性评论:我正在与空字符串进行松散比较,因为它看起来像您希望的示例所示.如果您想对要删除的确切元素更挑剔,请相应地自定义条件.

Obligatory comment: I 'm using a loose comparison with the empty string because it looks like what you intend given your example. If you want to be more picky about exactly which elements to remove then please customize the condition accordingly.

更新:奖金标记性的PHP丑陋代码可能会更快

我想到,如果在数组的开头和结尾有很多空元素,则上述方法可能不是最快的方法,因为它会逐个删除它们,并在每个步骤中重新索引数组,依此类推.一种适用于任何阵列的解决方案,只需一步即可完成修剪.警告:丑陋.

It occurred to me that if there are lots of empty elements at the beginning and end of the array the above method might not be the fastest because it removes them one by one, reindexing the array in each step, etc. So here's a solution that works for any array and does the trimming in just one step. Warning: ugly.

$firstNonEmpty = 0;
$i = 0;
foreach ($array as $val) {
    if ($val != '') {
        $firstNonEmpty = $i;
        break;
    }
    ++$i;
}

$lastNonEmpty = $count = count($array);
end($array);
for ($i = $count; $i > 0; --$i) {
    if (current($array) != '') {
        $lastNonEmpty = $i;
        break;
    }
    prev($array);
}

$array = array_slice($array, $firstNonEmpty, $lastNonEmpty - $firstNonEmpty);

实际操作中 .

这篇关于PHP从数组两侧删除空项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆