I want to return first 5 items from array. How can I do this?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
array_splice — Remove a portion of the array and replace it with something else:
From PHP manual:
If length is omitted, removes everything from offset to the end of the array. If length is specified and is positive, then that many elements will be removed. If length is specified and is negative then the end of the removed portion will be that many elements from the end of the array. Tip: to remove everything from offset to the end of the array when replacement is also specified, use count($input) for length .
If you just want to output the first 5 elements, you should write something like:
If you want to write a function which returns part of the array, you should use array_slice:
You can use array_slice function, but do you will use another values? or only the first 5? because if you will use only the first 5 you can use the LIMIT on SQL.
array_slice
returns a slice of an arrayis the code you want in your case to return the first five elements
A more object oriented way would be to provide a range to the #[] method. For instance:
Say you want the first 3 items from an array.
numbers = [1,2,3,4,5,6]
numbers[0..2] # => [1,2,3]
Say you want the first x items from an array.
numbers[0..x-1]
The great thing about this method is if you ask for more items than the array has, it simply returns the entire array.
numbers[0..100] # => [1,2,3,4,5,6]