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

查看:92
本文介绍了什么是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天全站免登陆