Skip to main content

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

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.

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];
//aray_pad
$new_array = array_pad($array, -(count($array)+1), 0);
//aray_splice
array_splice($array, 0, 0, 0);
//loop
for ($i = count($array); $i > 0; $i--) {
    $array[$i] = $array[$i-1];
}

$array[0] = 0;

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