Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get the last 3 elements of an array

Tags:

arrays

php

I have an array:

[13] => Array         (             [0] => joe             [1] => 0      [14] => Array         (             [0] => bob             [1] => 0         )      [15] => Array         (             [0] => sue             [1] => 0         )      [16] => Array         (             [0] => john             [1] => 0         )      [17] => Array         (             [0] => harry             [1] => 0         )      [18] => Array         (             [0] => larry             [1] => 0         ) 

How can I get the last 3 elements while preserving the keys? (the number of elements in the array may vary, so I cannot simply slice after the 2nd element)

So the output would be:

  [16] => Array         (             [0] => john             [1] => 0         )      [17] => Array         (             [0] => harry             [1] => 0         )      [18] => Array         (             [0] => larry             [1] => 0         ) 
like image 637
alex Avatar asked Mar 29 '11 06:03

alex


People also ask

How do I find the last 5 elements of an array?

To get the last N elements of an array, call the slice method on the array, passing in -n as a parameter, e.g. arr. slice(-3) returns a new array containing the last 3 elements of the original array. Copied!

How can we get the last element of an array in PHP?

You can use the end() function in PHP to get the last element of any PHP array. It will set the internal pointer to the last element of the array and return its value.

How do you find the first three values of an array?

Use the Array. slice() method to get the first N elements of an array, e.g. const first3 = arr. slice(0, 3) . The slice() method will return a new array containing the first N elements of the original array.

What is use of Array_slice in PHP?

The array_slice() function returns selected parts of an array. Note: If the array have string keys, the returned array will always preserve the keys (See example 4).


1 Answers

If you want to preserve key, you can pass in true as the fourth argument:

array_slice($a, -3, 3, true); 
like image 108
Andreas Wong Avatar answered Nov 09 '22 01:11

Andreas Wong