What is array_unshift() in PHP with Examples?

In PHP, the array_unshift() function is used to add one or more elements to the beginning of an array.

This function allows you to prepend elements to the front of an array, which can be particularly useful in various situations.

In this article, we will explore how to use array_unshift() in PHP, its syntax, and practical examples.

1. Syntax of array_unshift()

The array_unshift() function has the following syntax:

array_unshift(array &$array, mixed $value1 [, mixed $value2 [, mixed $... ]]): int

The function returns the new number of elements in the array after the operation.

2. Using array_unshift() to Prepend Elements

Here's an example of how to use array_unshift() to prepend elements to an array:

$colors = ["green", "blue", "yellow"];
array_unshift($colors, "red", "orange");



    [0] => red
    [1] => orange
    [2] => green
    [3] => blue
    [4] => yellow

In this example, we start with an array $colors containing three elements. We use array_unshift() to prepend the elements "red" and "orange" to the beginning of the array. As a result, the array now contains five elements, with the newly added elements at the front.

3. Prepending Multiple Elements with array_unshift()

You can also use array_unshift() to prepend multiple elements at once. Here's an example:

$fruits = ["apple", "banana"];
$moreFruits = ["orange", "grape"];
array_unshift($fruits, ...$moreFruits);



    [0] => orange
    [1] => grape
    [2] => apple
    [3] => banana

In this example, we have two arrays: $fruits and $moreFruits. We use the spread operator (...) to prepend the elements from $moreFruits to the beginning of $fruits. The result is a combined array with all elements, and the newly added elements are at the front.

4. Practical Use Cases for array_unshift()

The array_unshift() function is handy in various scenarios, such as:

  1. Adding Items to a Stack: You can use it to implement a stack data structure, where you add elements to the top of the stack.

  2. Inserting Items at the Beginning: When you need to insert items at the beginning of an existing list or queue, this function is helpful.

  3. Prepending Default Values: You can prepend default values to an array before adding or merging other values.

  4. Creating Dynamic Lists: It's useful for creating dynamic lists that start with predefined elements.



array_unshift() in PHP is a valuable function for adding elements to the beginning of an array. It's versatile and useful in various programming scenarios. Understanding how to use array_unshift() can help you efficiently manage arrays and data structures in your PHP applications, making it a valuable tool in your programming toolbox.