Skip to content
Advertisement

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

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
        )

Advertisement

Answer

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

array_slice($a, -3, 3, true);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement