How to Prepend an Element to an Array in PHP

Updated: January 10, 2024 By: Guest Contributor Post a comment

Overview

Prepending an element to an array in PHP can fundamentally alter the structure of the array. This operation adds a new item at the beginning of the array, shifting all the existing elements towards the end. PHP provides built-in functions to accomplish this task easily.

Using array_unshift()

The array_unshift() function is the simplest way to add an element to the start of an array. Here’s a basic example:

<?php
$fruits = ['apple', 'banana', 'cherry'];
array_unshift($fruits, 'apricot');
print_r($fruits);
?>

Output:

Array
(
    [0] => apricot
    [1] => apple
    [2] => banana
    [3] => cherry
)

array_unshift() also allows you to prepend multiple elements at once:

<?php
$fruits = ['apple', 'banana', 'cherry'];
array_unshift($fruits, 'apricot', 'avocado');
print_r($fruits);
?>

Output:

Array
(
    [0] => apricot
    [1] => avocado
    [2] => apple
    [3] => banana
    [4] => cherry
)

Prepending Elements with Array Addition

Another method to prepend an element to an array is by using the “array addition” operator. This can be particularly useful for associative arrays:

<?php
$fruits = ['a' => 'apple', 'b' => 'banana'];
$fruits = ['c' => 'cherry'] + $fruits;
print_r($fruits);
?>

Output:

Array
(
    [c] => cherry
    [a] => apple
    [b] => banana
)

Prepending to Multi-dimensional Arrays

Sometimes you need to add elements at the beginning of a multi-dimensional array:

<?php
$multiFruits = [
    ['name' => 'apple', 'color' => 'red'],
    ['name' => 'banana', 'color' => 'yellow']
];
array_unshift($multiFruits, ['name' => 'cherry', 'color' => 'red']);
print_r($multiFruits);
?>

Output:

Array
(
    [0] => Array
        (
            [name] => cherry
            [color] => red
        )

    [1] => Array
        (
            [name] => apple
            [color] => red
        )

    [2] => Array
        (
            [name] => banana
            [color] => yellow
        )
)

Performance Considerations

While array_unshift() is convenient, it can be less performant for very large arrays because it needs to reindex the array. If performance is critical, consider using alternative data structures like linked lists, or optimize array usage according to your application’s needs.

Conclusion

In conclusion, PHP makes it very easy to prepend elements to an array using the array_unshift() function, the array addition operator for associative arrays, or special considerations for multi-dimensional arrays. Remember to take into account performance when dealing with large arrays, and choose the right method that suits your application’s requirements.