Slicing an array means printing some elements of an array for a specified range using their index positions.
To slice an array in PHP, use the array_slice()
in-built PHP array function.
This function takes in the array to be sliced, and an offset (the index to start from). It can take other parameters like the number of elements to return (like a delimiter). The function has a definition:
array_slice(
array $array, // Array to be sliced
int $offset, // Slice starting point
?int $length = null, // Number of elements to take
): array
The function always returns an array from the original array.
<?// Create array of numbers$numbers = [1, 23, 4, 12, 45, 5, 56];// Get numbers from index 3 till the end$sliced = array_slice($numbers, 3);// Output the new arrayprint_r($sliced); // Returns [12, 45, 5, 56]
In this example, the array is sliced, starting from the fourth element (index 3). It takes this element and all the elements after it and forms a new array that is returned.
<?php// Create array of letters$letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];/**Slice the array to 4 letters,starting from the letter at index 3.**/$sliced = array_slice($letters, 3, 4);// Output resulting arrayprint_r($sliced); // Returns ['d', 'e', 'f', 'g']
In this example, four elements are taken out of the $letters
array. These elements are taken in the order we arranged. It starts from the fourth element (‘d’) and stops once four elements are taken.