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

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

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Slicing Associative Arrays in PHP Without Losing Keys

Working with numeric arrays in PHP is straightforward: you grab the last three elements using array_slice with a negative offset, and the keys shift predictably. However, once you move to associative arrays—where keys are explicit identifiers rather than sequential integers—the behavior changes subtly but significantly. If your goal is to extract the final three items while preserving their original keys, simply relying on standard slicing logic can lead to lost data or misaligned indices if not handled correctly.

The core challenge lies in understanding how array_slice interacts with associative arrays. When you use a negative offset like -3, PHP calculates the start position based on the total count of elements. Crucially, this operation preserves the original keys of the subset being sliced. This means that unlike re-indexing operations which might reset keys to 0, 1, 2, array_slice maintains the integrity of the key-value pairs found at the end of the array.

Consider an array where the last three entries have keys 16, 17, and 18. If you apply array_slice($arr, -3), PHP returns a new array containing exactly those three elements. The resulting array will have keys 16, 17, and 18 intact. This behavior is consistent regardless of whether the array contains hundreds of elements or just a few; the function dynamically calculates the start index based on the current length, making it robust for variable dataset sizes.

$data = [
    13 => ['name' => 'joe', 'age' => 0],
    14 => ['name' => 'bob', 'age' => 0],
    15 => ['name' => 'sue', 'age' => 0],
    16 => ['name' => 'john', 'age' => 0],
    17 => ['name' => 'harry', 'age' => 0],
    18 => ['name' => 'larry', 'age' => 0],
];

$lastThree = array_slice($data, -3);

In this example, $lastThree will contain the entries for John, Harry, and Larry with their original keys (16, 17, 18). This approach is efficient because it avoids iterating through the entire array to find the start point; PHP handles the calculation internally in linear time relative to the slice size.

A common pitfall arises when developers attempt to use loops or manual counting to achieve this result. While looping allows for full control, it introduces unnecessary overhead and increases the risk of off-by-one errors. For instance, trying to count backwards from the last index manually can be error-prone if the array structure changes unexpectedly. Using array_slice with a negative offset is the idiomatic PHP solution because it leverages the language's internal optimizations and guarantees key preservation without extra code complexity.

If you are working within a Laravel application, this pattern remains equally valid. While Laravel provides powerful collection methods like take() on collections, those methods often re-index keys unless explicitly told otherwise. If you are passing raw arrays to external libraries or functions that expect specific key associations, using the built-in array_slice function ensures compatibility without needing to convert everything to a Collection first.

The only scenario where this simple approach might fail is if the array itself is empty or contains fewer than three elements. In such cases, array_slice gracefully returns an array with whatever elements are available, up to the requested count, rather than throwing an error. This makes it a safe default for production code where data volume fluctuates.

Our network