PHP array_push
Summary: in this tutorial, you will learn how to add an element to the end of an array by using the PHP array_push()
function.
Introduction to the PHP array_push() function
The array_push()
function adds one or more elements to the end of an array. The syntax of the array_push()
function is as follows:
array_push ( array &$array , mixed ...$values ) : int
Code language: PHP (php)
In this syntax:
$array
is the input array.$values
is one or more elements to push onto the end of the input array.
The array_push()
function returns the new number of elements in the array.
Note that the array_push() function modifies the input array.
The array_push()
has the same effect as the following statement repeated for each new value:
$array[] = $value;
Code language: PHP (php)
If you just add one value to an array, you should use the statement $array[] = $value;
to avoid the overhead of calling the array_push()
function.
PHP array_push() function examples
The following example shows how to use the array_push()
function to add multiple elements to the end of an array:
$numbers = [1, 2, 3];
array_push($numbers, 4, 5);
print_r($numbers);
Code language: HTML, XML (xml)
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Code language: PHP (php)
In this example, we push the number 4 and 5 to the end of the $numbers
array.
Push an element to the end of an associative array
To add an element to an associative array, you use the following syntax:
$array[$key] = $value;
Code language: PHP (php)
In this case, you can’t use the array_push()
function. For example:
$roles = [
'admin' => 1,
'editor' => 2
];
$roles['approver'] = 3;
print_r($roles);
Code language: HTML, XML (xml)
Output:
Array
(
[admin] => 1
[editor] => 2
[approver] => 3
)
Code language: PHP (php)
Summary
- Use the PHP
array_push()
function to add one or more elements to the end of an array.