Only keep the first N elements of an array in PHP?

2020-07-03 04:40发布

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?

标签: php arrays
1条回答
一夜七次
2楼-- · 2020-07-03 05:16

You can use array_slice or array_splice:

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

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.

查看更多
登录 后发表回答