How to Add Elements to the Beginning of a PHP Array

Using the array_unshift() function you can easily add or insert new elements at the first position of an array in PHP.

The array_unshift() function takes the array you want to modify as its first argument, followed by the elements you want to add.

Here’s how you can use it:

Syntax of “array_unshift()”

array_unshift(array &$array, mixed ...$values): int

Example of Inserting Item at the beginning of an array

<?php
// Initial array
$fruits = array("banana", "orange", "apple");

// Add elements to the beginning
array_unshift($fruits, "strawberry", "blueberry");

// Print the modified array
print_r($fruits);
?>

Output:

Array
(
    [0] => strawberry
    [1] => blueberry
    [2] => banana
    [3] => orange
    [4] => apple
)