B. Bence
B. Bence

Reputation: 83

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);
}

This function returns with an array containing 3, but I'd like to return with an array containing 1 and 2, is this possible somehow?

Upvotes: 1

Views: 41

Answers (2)

Erik Kalkoken
Erik Kalkoken

Reputation: 32747

If you want to return the the remaining part of the array, use array_diff.

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

Upvotes: 0

Ben
Ben

Reputation: 9001

array_slice() takes up to four parameters:

array The input array.

offset If offset is non-negative, the sequence will start at that offset in the array. If offset is negative, the sequence will start that far from the end of the array.

length If length is given and is positive, then the sequence will have up to that many elements in it. If the array is shorter than the length, then only the available array elements will be present. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array.

preserve_keys Note that array_slice() will reorder and reset the numeric array indices by default. You can change this behaviour by setting preserve_keys to TRUE.

You can return the first 2 elements in the array by using the offset and length parameters together, like so:

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

As a rule, return the first x elements with:

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

Upvotes: 5

Related Questions