How to Slice an Array in PHP


In this tutorial, we go over how to slice an array in PHP.

Slicing an array means cutting off part of the whole array so that you only have a part of the array remaining in the end. Essentially, you're cutting off part of it.

Any part of an array can be sliced off.

Below is an example of an array:

(Greg, Steve, John, Harry, Tom, Bill, Dwayne)

Now the array is sliced from John all the way to the end of the array to Dwayne, so that it leaves the following array:

(John, Harray, Tom, Bill, Dwayne)

So Greg and Steve got sliced out of the array.

This is what is meant by slicing an array, cutting off or erasing part of the array.

To slice an array in PHP, we use the array_slice function following the general syntax below:

array_slice ($array, $index, $len)

$array is the original array in which you want to slice
$index is the index number of the element that you start at and want to keep
$len is the number of elements that you want to keep

Array_slice returns part of an array starting from $index and containing $len elements. If $len is omitted, it returns the elements to the end of the array.


$Students= array('Greg', 'Lisa', 'Bobby', 'Tom', 'Troy', 'Matthew', 'Peter', 'John');
$Students_going_on_trip= array_slice($Students, 2);
echo implode (', ', $Students_going_on_trip);

Actual PHP Output

Bobby, Tom, Troy, Matthew, Peter, John

The above array originally has 8 elements, representing 8 names of students.

Here we only specify the $array and the $index. Since we specify an index of 2, we cut off all elements before index 2. Thus, 'Greg' and 'Lisa' are cut off, since they are before index 2. We start at the name 'Bobby'. Since we don't specify the length of elements we want, we keeps all elements to the end of the array.

Now let's take the same array as above and slice not to the end but up until Matthew, which is index element 5. The PHP Code to do this would be:

$Students= array('Greg', 'Lisa', 'Bobby', 'Tom', 'Troy', 'Matthew', 'Peter', 'John');
$Students_going_on_trip= array_slice($Students, 2, 4);
echo implode (', ', $Students_going_on_trip);

All we have to do is specify the number 4, because from index 2 to index 5, there are 4 elements ( 2, 3, 4, 5). This will slice the array from Bobby to Matthew.

Actual PHP Output

Bobby, Tom, Troy, Matthew

HTML Comment Box is loading comments...