PHP get the last 3 elements of an associative array while preserving the keys?

PhpArrays

Php Problem Overview


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
        )

Php Solutions


Solution 1 - Php

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

array_slice($a, -3, 3, true);

Solution 2 - Php

Use array_slice:

$res = array_slice($array, -3, 3, true);

Solution 3 - Php

You can use array_slice with offset as -3 so you don't have to worry about the array length also by setting preserve_keys parameter to TRUE.

$arr = array_slice($arr,-3,3,true);                                             

Solution 4 - Php

You can use array_slice():

<?php
    // -3 = start from the end
    // true = preserve_keys
    $result = array_slice($array, 0, -3, true); 
?>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalexView Question on Stackoverflow
Solution 1 - PhpAndreas WongView Answer on Stackoverflow
Solution 2 - PhpfabrikView Answer on Stackoverflow
Solution 3 - PhpcodaddictView Answer on Stackoverflow
Solution 4 - PhpSilver LightView Answer on Stackoverflow