Using PHP array_unshift to Insert Elements at the Beginning of an Array

This article explains PHP's array_unshift function, showing its syntax, how to prepend single or multiple elements to an array, and provides clear code examples with output to demonstrate its effect on both string and numeric arrays.

php Courses
php Courses
php Courses
Using PHP array_unshift to Insert Elements at the Beginning of an Array

PHP is a widely used server‑side scripting language for creating dynamic web pages, and arrays are a fundamental data structure for storing collections of values.

The built‑in function array_unshift inserts one or more elements at the beginning of an array and returns the new number of elements. Its syntax is:

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

In the first example, an array of fruits is defined, the function is used to prepend the string “grape”, and the before/after states are printed, showing “grape” now at index 0.

<?php
$fruits = array("apple", "orange", "banana");
echo "Before array_unshift: ";
print_r($fruits);

array_unshift($fruits, "grape");
echo "After array_unshift: ";
print_r($fruits);
?>

The output confirms the element was added at the start of the array.

A second example demonstrates inserting multiple values (1 and 2) into a numeric array, again showing the updated order after the call.

<?php
$numbers = array(3, 4, 5);
echo "Before array_unshift: ";
print_r($numbers);

array_unshift($numbers, 1, 2);
echo "After array_unshift: ";
print_r($numbers);
?>

Both examples illustrate that array_unshift provides a convenient way to prepend elements without manually re‑indexing the array, making it useful in real‑world PHP projects.

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.

PHPTutorialArraysarray_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.