如何使用 array_slice 返回包含已删除元素的数组,而不是从中删除元素的数组


How to return an array containing the removed elements instead of the array from which the elements was removed using array_slice

function take()
{
$array = [1, 2, 3];
return array_slice($array, 2);
}
这个函数返回一个包含 3 的数组,

但我想返回一个包含 1 和 2 的数组,这可能吗?

array_slice()最多需要四个参数:

数组输入数组。

抵消如果偏移量为非负数,则序列将从数组中的该偏移量开始。如果偏移量为负,则序列将从数组的末尾开始。

长度如果给定长度并且是正数,则序列中将包含多达这么多元素。如果数组短于长度,则仅存在可用的数组元素。如果给定长度并且为负数,则序列将从数组末尾停止许多元素。如果省略它,那么序列将包含从偏移量到数组末尾的所有内容。

preserve_keys请注意,默认情况下,array_slice(( 将重新排序和重置数字数组索引。您可以通过将preserve_keys设置为 TRUE 来更改此行为。

您可以通过同时使用偏移量和长度参数来返回数组中的前 2 个元素,如下所示:

function take()
{
    $array = [1, 2, 3];
    return array_slice($array, 0, 2);
}

通常,返回前x元素

$x = 2; //with $x being the number of elements to return from the start
return array_slice($array, 0, $x);
如果要

返回数组的其余部分,请使用 array_diff

function take()
{
   $array = [1, 2, 3];
   return array_diff ($array, array_slice($array, 2));
}