The JavaScript Array unshift() function is used to add one or more elements to the beginning of an array. It modifies the original array and returns the new length of the array. The elements are added in the order they appear in the function arguments. This function is useful when you want to add new elements to the beginning of an array without changing the order of the existing elements. Keep reading below to learn how to Javascript Array unshift in PHP.

Looking to get a head start on your next software interview? Pickup a copy of the best book to prepare: Cracking The Coding Interview!

Buy Now On Amazon

Javascript Array unshift in PHP With Example Code

JavaScript’s array unshift() method is a useful tool for adding elements to the beginning of an array. However, what if you’re working in PHP and need to achieve the same result? Fortunately, PHP provides a similar function that accomplishes this task: array_unshift().

To use array_unshift(), you simply need to pass in the array you want to modify as the first argument, followed by the elements you want to add to the beginning of the array as subsequent arguments. For example:


$myArray = array("apple", "banana", "cherry");
array_unshift($myArray, "orange", "pear");
print_r($myArray);

This code would output:


Array
(
[0] => orange
[1] => pear
[2] => apple
[3] => banana
[4] => cherry
)

As you can see, the array_unshift() function has added “orange” and “pear” to the beginning of the $myArray array.

It’s worth noting that array_unshift() modifies the original array rather than creating a new one. If you want to create a new array with the added elements, you can use the array_merge() function:


$myArray = array("apple", "banana", "cherry");
$newArray = array_merge(array("orange", "pear"), $myArray);
print_r($newArray);

This code would output:


Array
(
[0] => orange
[1] => pear
[2] => apple
[3] => banana
[4] => cherry
)

In summary, if you need to add elements to the beginning of an array in PHP, you can use the array_unshift() function. Just pass in the array you want to modify as the first argument, followed by the elements you want to add as subsequent arguments. If you want to create a new array with the added elements, you can use the array_merge() function.

Equivalent of Javascript Array unshift in PHP

In conclusion, the PHP array_unshift() function is the equivalent of the JavaScript Array unshift() function. It allows developers to add one or more elements to the beginning of an array, shifting the existing elements to higher indexes. This function is useful when you need to add new elements to the beginning of an array without overwriting the existing elements. By using array_unshift() in PHP, you can easily manipulate arrays and create dynamic applications that can handle a variety of data types. Whether you are a beginner or an experienced developer, understanding the array_unshift() function in PHP can help you write more efficient and effective code.

Contact Us