In this post, we will see how to return first n items from an array in PHP.

1. Using array_slice() function

The idea is to use array_slice() function that returns a slice of an array. It returns the sequence of elements from the array as specified by the offset and length parameters.

The following code extracts the first n items from an array using the array_slice() function.

Download  Run Code

 
For associative arrays, the code remains similar:

Download  Run Code

2. Using array_splice() function

Another solution is to use the array_splice() function, which replaces a portion of the array. It can be used to get the first n elements from an array. However, this may result in unexpected behaviour since array_splice() also remove the returned items from the input array.

The following code demonstrates the usage of the array_splice() function for removing and returning the first n items from an array.

Download  Run Code

That’s all about returning first n items from an array in PHP.