Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP extract part from array keeping previous keys

Tags:

arrays

php

slice

I have the array with specific keys. I want to get the first 5 array elements. I use array_splice(). All OK, but keys in the new array is 0, 1, 2, 3 ,4. And I want to keep the previous array keys. I can do it with foreach, but i am finding the elegant method.
My code:

$levels = array('a' => 1, 'b' =>2, 'c' => 3, 'd' => 4, 'f' => 5, 'g' => 6);
$levels = array_splice($levels, 5);

Thank you in advance. Sorry for my english.

like image 642
Alex Pliutau Avatar asked Jan 26 '11 12:01

Alex Pliutau


2 Answers

Try array_slice with $preserve_keys set to true.

like image 190
deceze Avatar answered Oct 23 '22 04:10

deceze


With array_slice, the original array is not modified:

$levels = array('a' => 1, 'b' =>2, 'c' => 3, 'd' => 4, 'f' => 5, 'g' => 6);
$firstLevels = array_slice($levels, 0, 5, true);
// count($levels) is 6, count($firstLevels) 5
like image 45
phihag Avatar answered Oct 23 '22 03:10

phihag