How do I move an array element with a known key to the end of an array in PHP?

How do I move an array element with a known key to the end of an array in PHP?

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

Stefan Bogdanescu

Founder & Senior Architect

Moving an Array Element to the End in PHP

You are facing a common structural challenge: you have an associative array where the order of insertion matters, but one specific key—'monkey'—must always reside at the end after all other data has been processed. The constraint is strict: you cannot disturb the relative order of the existing elements. If your array currently looks like ['giraffe', 'lion', 'monkey'], the target state must be ['giraffe', 'lion', 'monkey'] assuming 'monkey' was originally first, or effectively moving it from index 0 to the final position regardless of where it started.

The most efficient approach in modern PHP does not involve creating a new array and copying elements one by one. Instead, you can leverage built-in functions that handle indices directly. The standard pattern involves identifying the key's current position, removing it from that spot, and appending it to the end.

Consider a scenario where your array is populated dynamically:

$my_array = [
    'monkey'  => ['data' => 'start'],
    'giraffe' => ['data' => 'middle'],
    'lion'    => ['data' => 'end']
];

In this case, 'monkey' is at index 0. You need to move it so that the final structure preserves the order of giraffe and lion while placing monkey last.

The most direct solution uses array_splice() combined with array_push(). The logic is straightforward: extract the element from its current location and push it to the end.

$keyToMove = 'monkey';

// Find the index of the key
$index = array_search($keyToMove, array_keys($my_array));

if ($index !== false) {
    // Remove the element at $index (returns value, but we want the element itself)
    // Actually, array_splice modifies by reference or returns removed elements.
    // To move, we splice out the item and then push it.
    
    // However, a cleaner way to "move" without intermediate variables:
    // We can use array_splice with negative offset logic? No, splicing removes.
    
    // The robust one-liner approach:
    $my_array = array_merge(
        array_slice($my_array, 0, $index), 
        array_slice($my_array, $index + 1), 
        [$keyToMove] => array_pop($my_array) // Wait, this destroys the value.
    );
}

Wait, that logic above is flawed because array_pop loses the data. The correct, high-performance idiom relies on array_splice to remove the element and then reconstructing the array with the element appended. However, since you are dealing with an associative array, simply re-indexing might lose keys if not handled carefully.

Actually, there is a much simpler, albeit slightly verbose, method that preserves the values perfectly without needing to know the index beforehand, though knowing the key helps:

$key = 'monkey';
$my_array = []; // Re-initialize or use the existing array reference

// Extract the specific element
$element = $my_array[$key];

// Remove it from the original array using splice on keys? 
// No, standard array_splice works on indices.

// The most efficient algorithmic approach:
// 1. Identify the index of the target key.
// 2. Slice the array into two parts: before and after the target.
// 3. Concatenate the "after" part, then the "target" element as a new item at the end.

$index = array_search($key, array_keys($my_array));

if ($index !== false) {
    // Part 1: Everything before 'monkey'
    $before = array_slice($my_array, 0, $index);
    
    // Part 2: Everything after 'monkey'
    $after = array_slice($my_array, $index + 1);
    
    // Reconstruct with 'monkey' at the end. 
    // We must ensure we keep the original value associated with 'monkey'.
    $final_element = array_shift([$key => $element]); 
    
    $my_array = array_merge($before, $after, [$key => $final_element]);
}

While this works, it involves multiple passes and memory allocations for slicing. Is there a way to do this with fewer operations? In PHP, true "moving" of an element in place is not natively supported by a single atomic function because arrays are maps, not just stacks. You generally have to reconstruct the order.

However, if you are using Laravel, you might consider whether your data structure truly requires an associative array for this specific logic. If the order is paramount and keys are incidental, converting to a numeric indexed array temporarily can simplify the manipulation. But if those keys ('giraffe', 'lion') carry semantic meaning required by downstream code, you must preserve them.

The trade-off here is performance versus complexity. For small arrays, array_merge with slices is negligible in cost. For massive datasets, maintaining a separate counter or using a linked list structure might be overkill, but if this operation happens inside a tight loop, the overhead of slicing could accumulate.

A common pitfall developers face is assuming that removing an element shifts the rest automatically while keeping the original keys intact for the subsequent elements. array_splice does shift indices, but if you are relying on key preservation for the "after" part, you must be careful not to overwrite keys with new numeric ones unless you intend to re-index the whole structure.

If the goal is strictly to ensure 'monkey' is last without altering the order of others, the array_merge approach described above is the standard, readable solution. It explicitly defines the boundaries of the split and the insertion point, making the intent clear to any developer reading the code. There are no hidden constants or magic functions that move associative array keys in place; the reconstruction pattern is the intended idiomatic PHP way to handle this specific ordering requirement.

Our network