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 )
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!
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.
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.
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).
If you want to preserve key, you can pass in true as the fourth argument:
array_slice($a, -3, 3, true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With