How to use array_slice()
In this lesson we look at how we can extract part of an array using array_slice().
The format for the array_slice() function is:
array_slice(array, offset, length)
Suppose we have an array of letters as follows:
Line 1: this is our opening PHP code block declaration.
Line 2: we have an array called $letters which contains the letters a to g.
Now suppose we wish to ignore the first 3 values in the array and return the remaining values.
The value 3 is called the offset. In this case it literally means begin slicing the array at the 4th value (the one at position 3 in the array). Remember, array values start at the 0 position.
The $output array in this case will be a subset of the array containing the letters d, e, f, and g.
If we wanted to return the 4th, and 5th letters then we can specify another argument in our array_slice() function. The third argument is the length i.e. how many values we wish to return. In this case we are returning 2 values.
In this case the returned letters would be d and e.
What if we don't know the length of the array and want to return the last 3 values of the array?
Well, we can use a negative offset. Imagine that we go backwards from position 0. We know there is nothing actually at position -1. However, we actually say that the last value is in position -1 and the next is position -2 etc.
In our previous example this would mean that letter g is in position -1 and letter f is in position -2.
We can now do the following:
Line 4: We slice the array starting at position -3 and return 3 values.