The php array_slice() function gives us the ability to slice an array and extract elements at specific positions.
$array = array('bear', 'elephant', 'rabbit', 'salmon', 'alligator', 'whale');
// Slice array from position 1 to 3
print_r(array_slice($array, 1, 2));
// Output:
Array
(
[0] => elephant
[1] => rabbit
)
When working with collections of data in php, the ability to add to, remove from, and manipulate those collections is valuable.
The php array_slice() function allows us extract slices from arrays.
array_slice() takes two required parameter and two optional parameters. The required parameters are the array you want to slice from, and the starting position of the slice.
The optional parameters are the length of the slice and if you want to preserve the keys of the array.
If you don’t pass a length to array_slice(), you get the entire array after the passed starting position.
Below is an example of how to use array_slice() to get a slice of an array in php.
$array = array('bear', 'elephant', 'rabbit', 'salmon', 'alligator', 'whale');
// Slice array from position 1 to 3
print_r(array_slice($array, 1, 2));
// Output:
Array
(
[0] => elephant
[1] => rabbit
)
Preserving Keys with array_slice() in php
By default, keys are reindexed after taking a slice with array_slice().
The fourth parameter to array_slice() allows you to preserve the existing keys after taking a slice.
Below shows the difference between the default behavior and using the preserve keys parameters with array_slice().
$array = array('bear', 'elephant', 'rabbit', 'salmon', 'alligator', 'whale');
print_r(array_slice($array, 1, 2));
print_r(array_slice($array, 1, 2, true));
// Output:
Array
(
[0] => elephant
[1] => rabbit
)
Array
(
[1] => elephant
[2] => rabbit
)
Getting the Last Element of an Array with array_slice() in php
One useful application of array_slice() is to get the last element of an array in php.
To get the last element of an array in php, pass ‘-1’ to array_slice(). You don’t need to pass an ending position since by default the ending position is the end of the array.
Below is a example of how to get the last element of an array with array_slice() using php.
$array = array(1, 2, 3, 4, 5);
echo array_slice($array, -1)[0];
// Output:
5
Hopefully this article has been useful for you to learn how to use array_slice() to extract slices from your arrays in php.