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.
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
