I have an associative array like follow
Array ( [1274] => 2 [2700] => 3 [2701] => 4 [2702] => 2 [2699] => 2 [2698] => 1 [2694] => 1......)
what i want is to take the first 10 elements from this array. I Used array_slice
. But then the new array will be like
Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 2 [4] => 2 [5] => 1 [6] => 1.....)
It limits the array but array keys have been removed. How can i get the keys as well? Thanks for your advices.
Well, you could do something like this:
$slice = array_intersect_key($whole,array_flip(array_slice(array_keys($whole),0,10)));
If you want something more readable, this'll work:
$keys = array_keys($whole);
$slice = Array();
$firstkeys = array_slice($keys,0,10);
foreach($firstkeys as $key) $slice[$key] = $whole[$key];
You can limit an iteration on the array and convert it back to an array:
$first = iterator_to_array(new LimitIterator(new ArrayIterator($array), 0, 10));
Try this :
$res = array_chunk($array,10,true);
echo "<pre>";
print_r($res[0]);
If you want to know the second set of 10 just print_r($res[1]);