(Correction) get portion of array while maintaining indexes
I have an easy question that I can'开发者_开发知识库t seem to get my head around. Let say I have an associative array:
$myArray = array(
145 => 'Ferrari',
146 => 'Lamborghini',
147 => 'Mustang',
148 => 'Acura',
149 => 'Honda'
);
How do I return let say the last n elements from that array while maintaining the key association. I tried array_slice, but I keep getting an empty array
Any help please Thank you
Fourth parameter of array_slice is $preserve_keys.
You may want to use array_slice()
with the optional fourth argument
array array_slice ( array $array , int $offset [, int $length [, bool $preserve_keys = false ]] )
$var = array_slice($myArray, -3, 3, true);
you can pass the preserve_keys
parameter the value of true
in array_slice to keep your keys.
One of the problems with this is the word "last". In an associative array, there is no "first" or "last". So you'll have to define what you want. Do you want the last 3 when sorted alphabetically? etc. Once the question is defined in such terms, the answer will become much more apparent.
精彩评论