What PHP function do you use to get a specific number of items from an array in PHP?

Question by Peter: What PHP function do you use to get a specific number of items from an array in PHP?
You want to only get the first 5 items from an array, but if there only exists less than 5 items in the array, you still want to get them all.

The result would be an array variable containing at most 5 items.
Is there a single PHP function that can do this? (I want to avoid using any loop or if statement)

Many thanks to you all.

Best answer:

Answer by Purple Moogle
You could do this quite easily using the following:

$ result = array();
$ num = 0;
while($ num<=5 && isset($ itemarray[$ num])) { $ result[] = $ itemarray[$ num]; $ num++; } You can use array_slice(array, offset, length, preservekeys) though. The arguments are rather obivously the array to slice from, the number to start from, the number of elements to slice and whether or not to preserve the original keys or not (not will just generate sequential keys).

Give your answer to this question below!

Comments are closed.