How to Use PHP’s array_unshift to Add Elements at the Beginning of an Array

This guide explains PHP’s array_unshift function, covering its syntax, how it inserts one or multiple values—including other arrays—at the start of an existing array, provides step‑by‑step code examples, highlights that it modifies the original array, and notes practical use cases such as shopping carts and blog post lists.

php Courses
php Courses
php Courses
How to Use PHP’s array_unshift to Add Elements at the Beginning of an Array

array_unshift() Syntax

The array_unshift() function adds one or more elements to the beginning of an array and returns the new length of the array.

array_unshift(array, value1, value2, ...)

Example: Adding a Single Element

$fruits = array("apple", "banana", "cherry");
array_unshift($fruits, "orange");

Resulting array:

array("orange", "apple", "banana", "cherry")

Example: Adding Multiple Elements

array_unshift($fruits, "pear", "grape");

Resulting array:

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

Example: Adding an Array

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

Resulting array:

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

Important Considerations

Because array_unshift() modifies the original array, you should back up the array beforehand if you need to preserve the original data.

Conclusion

array_unshift()

is a versatile PHP function for prepending one or more values—whether strings, numbers, booleans, or even another array—to the start of an existing array, making it useful in scenarios such as adding new items to a shopping‑cart list or inserting the latest post at the top of a blog feed.

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.

PHParray_unshiftphp-tutorialphp arrays
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.