PHP array_unshift
Summary: in this tutorial, you will learn how to use the PHP array_unshift()
function to prepend one or more elements to the beginning of an array.
Introduction to the PHP array_unshift() function
To prepend one or more elements to an array, you use the array_unshift()
function:
array_unshift ( array &$array , mixed ...$values ) : int
Code language: PHP (php)
In this syntax:
$array
is the input array$values
is the values to prepend
The array_unshift()
returns the new number of elements in the array.
Note that the array_unshift()
function modifies the original array. The array_unshift()
function prepends the elements to the input array as a whole. It preserves the prepended elements.
Since the array_unshift()
function adds the new elements to the beginning of the input array, it changes the indexes to start from zero.
PHP array_unshift() examples
Let’s take some examples of using the PHP array_unshift()
function.
1) Using PHP array_unshift() function to prepend one element to an array example
The following example uses the array_unshift()
function to prepend an element to the beginning of an array:
$permissions = [
'edit',
'delete',
'view'
];
array_unshift($permissions, 'new');
print_r($permissions);
Code language: HTML, XML (xml)
Output:
Array
(
[0] => new
[1] => edit
[2] => delete
[3] => view
)
Code language: plaintext (plaintext)
How it works.
- First, define an array with three elements.
- Second, prepend the
'new'
element to the beginning of the array. - Third, show the elements of the array using the
print_r()
function.
As you can see clearly from the output, the 'new'
element gets the index zero while the existing indexes change accordingly.
2) Using PHP array_unshift() function to prepend one element to an array example
The following example uses the array_unshift()
to prepend three elements to the beginning of an array:
$permissions = [
'edit',
'delete',
'view'
];
array_unshift($permissions, 'new', 'approve', 'reject');
print_r($permissions);
Code language: HTML, XML (xml)
Output:
Array
(
[0] => new
[1] => approve
[2] => reject
[3] => edit
[4] => delete
[5] => view
)
Code language: plaintext (plaintext)
Prepending an element to the beginning of an associative array
To prepend an element to an associative array, you use the + operator. For example:
$colors = [
'red' => '#ff000',
'green' => '#00ff00',
'blue' => '#0000ff',
];
$colors = ['black' => '#000000'] + $colors;
print_r($colors);
Code language: HTML, XML (xml)
Output:
Array
(
[black] => #000000
[red] => #ff000
[green] => #00ff00
[blue] => #0000ff
)
Code language: PHP (php)
Summary
- Use the PHP
array_prepend()
function to preprend one or more elements to the beginning of an array.