How to Add Elements to a PHP Array with array_unshift
This article provides a quick guide on how to use PHP’s native
array_unshift() function to add one or more elements to the
beginning of an array. You will learn the function’s syntax, how it
handles both numerical and string keys, and how to implement it in your
code using clear, practical examples.
Understanding array_unshift()
The array_unshift() function prepends passed elements to
the front of an array. The list of elements is prepended as a whole,
meaning the passed elements remain in the same order they were passed
in.
Because this function modifies the array by reference, it alters the original array directly rather than returning a new one.
Syntax
array_unshift(array &$array, mixed ...$values): int$array: The input array.$values: The values to prepend to the start of the array.- Return Value: Returns the new number of elements in the array as an integer.
Practical Examples
Example 1: Adding a Single Element
When you prepend an element, all existing numerical keys are modified to start counting from zero, while literal (string) keys remain untouched.
$fruits = ["banana", "orange"];
array_unshift($fruits, "apple");
print_r($fruits);Output:
Array
(
[0] => apple
[1] => banana
[2] => orange
)
Example 2: Adding Multiple Elements
You can prepend multiple elements at once by passing them as separate arguments.
$numbers = [3, 4];
array_unshift($numbers, 1, 2);
print_r($numbers);Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Example 3: Behavior with Associative Keys
If your array contains string keys, those keys will remain unchanged.
Only numerical keys are reset. New prepended elements receive numerical
keys starting from 0.
$colors = ["b" => "green", "c" => "blue"];
array_unshift($colors, "red");
print_r($colors);Output:
Array
(
[0] => red
[b] => green
[c] => blue
)