array_pop() 数组中最后 n 个元素的最有效方法是什么? [英] What's the most efficient way to array_pop() the last n elements in an array?

查看:47
本文介绍了array_pop() 数组中最后 n 个元素的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

弹出数组中最后 n 个元素的有效方法是什么?

What's an efficient way to pop the last n elements in an array?

这是一个:

$arr = range(1,10);
$n = 2;
$popped_array = array();
for ($i=0; $i < $n; $i++) { 
    $popped_array[] = array_pop($arr);
}
print_r($popped_array); // returns array(10,9);

有没有更有效的方法?

推荐答案

使用 array_splice():

如果您要删除最后的n个元素,请使用以下函数:

If you're trying to remove the last n elements, use the following function:

function array_pop_n(array $arr, $n) {
    return array_splice($arr, 0, -$n);
}

演示

如果您只想检索最后的n个元素,那么您可以使用以下函数:

If you want to retrieve only the last n elements, then you can use the following function:

function array_pop_n(array $arr, $n) {
    array_splice($arr,0,-$n);
    return $arr;
}

演示

这篇关于array_pop() 数组中最后 n 个元素的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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