How to Use PHP's array_unshift() to Prepend Elements to an Array

This article explains the PHP array_unshift() function, its syntax, and how to prepend single or multiple values—including other arrays—to the beginning of an array, with code examples and practical usage tips, while warning about its in‑place modification behavior.

php Courses
php Courses
php Courses
How to Use PHP's array_unshift() to Prepend Elements to an Array

In PHP, arrays are a common data type that can store a series of values and be accessed by index.

Syntax of array_unshift()

The function array_unshift() adds one or more elements to the beginning of an array and returns the new number of elements. Its syntax is: array_unshift(array, value1, value2, ...) In this syntax, array is the target array, and value1, value2, etc., are the values to prepend. The function modifies the original array.

Usage Example

First create an array: $fruits = array("apple", "banana", "cherry"); Then prepend a new element: array_unshift($fruits, "orange"); After the call, $fruits becomes: array("orange", "apple", "banana", "cherry"); You can also prepend multiple values at once: array_unshift($fruits, "pear", "grape"); Resulting in:

array("pear", "grape", "orange", "apple", "banana", "cherry");

The function accepts values of any type, such as integers, floats, or booleans.

It can also prepend another array, making that array the first element:

$more_fruits = array("melon", "kiwi");
array_unshift($fruits, $more_fruits);

Now $fruits starts with the nested array:

array(array("melon", "kiwi"), "pear", "grape", "orange", "apple", "banana", "cherry");

Typical use cases include inserting a new product at the beginning of a shopping‑cart list or adding a newly published article to the top of a blog feed.

Precautions

Because array_unshift() modifies the original array, it is advisable to back up the array before calling the function to avoid accidental data loss.

Conclusion

The array_unshift() function is a practical tool for PHP developers to prepend elements to arrays, making array manipulation more flexible. Remember to back up your data before using it.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPArraysarray_unshift
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.