Return first `n` items from an array in PHP
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $arr = [1, 2, 3, 4, 5]; $n = 3; $slice = array_slice($arr, 0, $n); print_r($slice); /* Output: Array ( [0] => 1 [1] => 2 [2] => 3 ) */ ?> |
For associative arrays, the code remains similar:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php $arr = array("Nick"=>"20", "John"=>"10", "Paul"=>"18"); $n = 2; $slice = array_slice($arr, 0, $n); print_r($slice); /* Output: Array ( [Nick] => 20 [John] => 10 ) */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php $arr = array("Nick"=>"20", "John"=>"10", "Paul"=>"18"); $n = 2; $slice = array_splice($arr, 0, $n); print_r($slice); print_r($arr); /* Output: Array ( [Nick] => 20 [John] => 10 ) Array ( [Paul] => 18 ) */ ?> |
That’s all about returning first n items from an array in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)