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!

Table of Contents

array_unshift

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

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

array_unshift($movies , 'Titanic');
print_r($movies);

Output:

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

array_merge

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);
print_r($movies);

The output is the same as above.

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.

Close