Sling Academy
Home/PHP/How to Prepend an Element to an Array in PHP

How to Prepend an Element to an Array in PHP

Last updated: January 10, 2024

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.

Next Article: How to Get the Length of an Array in PHP

Previous Article: How to Insert an Element into an Array in PHP

Series: PHP Data Structure Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array