How to Insert an Item at the Beginning of An Array in PHP?

I’m sure you’ve been in a situation where you need to insert an item at the beginning of an array. For example, say your friend has just sent you their list of favorite movies and it looks like this: [“The Godfather”, “A Few Good Men”, “Jurassic Park”] but they want to add Titanic to the top. This is what we’ll do!


array_unshift() inserts elements at the beginning of an array.

$movies = ["The Godfather", "A Few Good Men", "Jurassic Park"];

array_unshift($movies , 'Titanic');


    [0] => Titanic
    [1] => The Godfather
    [2] => A Few Good Men
    [3] => Jurassic Park


array_merge() can combine the elements of one or more arrays together. This will add the values of the last array to the end of the first one. The function will return the new array that is created.

$movies = ["The Godfather", "A Few Good Men", "Jurassic Park"];

$movies = array_merge(['Titanic'], $movies);

The output is the same as above.

Other examples

All the methods below will print this output:

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 )
$array = [1, 2, 3, 4, 5];
$new_array = array_pad($array, -(count($array)+1), 0);
array_splice($array, 0, 0, 0);
for ($i = count($array); $i > 0; $i--) {
    $array[$i] = $array[$i-1];

$array[0] = 0;
Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.