仅在PHP中保留数组的前N个元素? [英] Only keep the first N elements of an array in PHP?

查看:459
本文介绍了仅在PHP中保留数组的前N个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法只能保留数组的前N个(例如10个)元素?我知道有array_pop,但是有没有更好,更优雅的方式?

Is there a way to only keep the first N (for example 10) elements of an array? I know there is array_pop, but is there a better, more elegant way?

推荐答案

您可以使用 array_slice array_splice :

You can use array_slice or array_splice:

$b = array_slice($a, 0, 10);
$c = array_splice($a, 0, 10);

请注意,array_slice复制$a的项目并返回它们,而array_splice会修改$a本身,并且仅返回已从$a中删除的项目.

Note that array_slice copies the items of $a and returns them while array_splice does modify $a itself and only returns the items that have been removed from $a.

这篇关于仅在PHP中保留数组的前N个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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