PHP Function Array_Slice
In the last article, Working With Array Elements in PHP, you learned how to read and change individual elements of an array. However, there are times where you may want to work with a range of array elements instead of just one. This is where the php function array_slice comes into play. In this article, you'll learn about the function, how to use it, and some practical examples of its usage.
The php function array_slice returns the selected part of an array based on its arguments. It takes four parameters, two of which are mandatory: the array and its starting position. The rest are optional: the length of the sequence (if specified), and the preserve_keys option, which if set to true will preserve the indexes of integer arrays; if not, they will be reset to zero.
If the length of the sequence is not specified, then the slice will contain everything from the start to the end of the array. This is a good way to quickly fetch just a specific part of an array, especially if the array has a lot of elements that you aren't interested in.
The length of the slice can also be specified if you'd like to take just a specific number of elements from an array. For example, if the array has five elements and you only want to take four of them, then you would specify the length as 4. You can also specify a negative value for the length if you'd like to start from the end of the array.