How to take care of your Dog?

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

Peter - 2009-08-21 03:26:39 - Programming Design

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:

use this function array_slice(array, offset, length, preservekeys) in your case the function call will be like this $result_array = array_slice($your_array, 0, 5 );

More Answers:

Purple Moogle - 2009-08-21 04:03:11
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).

Conan Fan - 2009-08-21 04:50:43
use this function array_slice(array, offset, length, preservekeys) in your case the function call will be like this $result_array = array_slice($your_array, 0, 5 );

map google sitemap
Copyright© Dog-Trader.com, it's all about Dogs | Privacy Policy | Puppy Training