PHP array_unshift Function
last modified March 13, 2025
The PHP array_unshift
function prepends one or more elements to
the beginning of an array. It modifies the original array and returns the new
count of elements.
Basic Definition
array_unshift
adds elements to the start of an array. All
numeric array keys are re-indexed starting from zero. String keys remain
unchanged.
Syntax: array_unshift(array &$array, mixed ...$values): int
. The
function returns the new number of elements in the array after prepending.
Basic array_unshift Example
This demonstrates adding a single element to the beginning of an array.
<?php $fruits = ["banana", "apple"]; $count = array_unshift($fruits, "orange"); print_r($fruits); echo "New count: $count";
The function adds "orange" to the start and returns 3, the new element count.
Adding Multiple Elements
array_unshift
can prepend multiple elements at once.
<?php $numbers = [3, 4]; $count = array_unshift($numbers, 1, 2); print_r($numbers); echo "New count: $count";
Both 1 and 2 are added to the start. The function returns 4, the new array length.
Associative Arrays
With associative arrays, numeric keys are re-indexed while string keys stay.
<?php $data = ["name" => "John", 0 => "apple"]; $count = array_unshift($data, "first"); print_r($data); echo "New count: $count";
Output shows the string key remains: Array ( [0] => first [name] => John
[1] => apple )
. The numeric key was re-indexed from 0 to 1.
Empty Array Handling
When used on empty arrays, array_unshift
simply adds elements.
<?php $empty = []; $count = array_unshift($empty, "a", "b"); print_r($empty); echo "New count: $count";
The function works the same way, adding elements to an empty array and returning the new count (2).
Return Value Usage
The return value can be used directly in expressions or assignments.
<?php $colors = ["red", "blue"]; if (array_unshift($colors, "green") > 2) { echo "Array now has more than 2 elements"; } print_r($colors);
This checks the return value immediately. Output shows the message and the
modified array: Array ( [0] => green [1] => red [2] => blue )
.
Best Practices
- Performance: Avoid frequent unshifts on large arrays.
- Clarity: Use for clear prepend operations only.
- Indexing: Be aware of numeric key re-indexing.
- Alternatives: Consider array_merge for complex cases.
Source
PHP array_unshift Documentation
This tutorial covered PHP's array_unshift
function with examples
showing how to prepend elements to arrays in different scenarios.
Author
List all PHP Array Functions.