OneBite.Dev - Coding blog in a bite size

Insert An Element At The Beginning Of An Array In PHP

Code snippet for how to Insert An Element At The Beginning Of An Array In PHP with sample and detail explanation

Working with arrays is a common task in PHP programming. One of the operations you might need to perform quite often is inserting an element at the beginning of an array. In this article, we are going to explore how to do just that.

Code snippet for inserting an element at the beginning of an array

Here’s a simple code snippet that illustrates how you can insert an element at the start of an array in PHP:

<?php
   $fruits = array("apple", "banana", "cherry");
   array_unshift($fruits, "pear");
   print_r($fruits);
?>

After executing this code, the $fruits array will look like this: Array ( [0] => pear [1] => apple [2] => banana [3] => cherry ).

Code Explanation for inserting an element at the beginning of an array

In the above code snippet, first, we define an array $fruits with three elements: ‘apple’, ‘banana’, and ‘cherry’.

Then we use the array_unshift() function to insert a new element at the beginning of the $fruits array. The array_unshift() function is a built-in PHP function specifically designed for this purpose. The first argument to this function is the array we want to modify. The subsequent arguments are the elements we want to add to the beginning of the array.

In our case, we pass $fruits and "pear" as arguments to array_unshift(). This inserts the string ‘pear’ at the beginning of the $fruits array.

Finally, we print the contents of the $fruits array using the print_r() function, which gives us the updated array.

It’s important to note that the array_unshift() function modifies the original array. If you want to keep the original array unchanged, you will need to make a copy of it before using array_unshift().

php