array_push() is a PHP built-in function that adds one or more elements to the end of an array. Its syntax is very simple:
array_push(array &$array, mixed ...$values): int
$array is the target array, note that it is passed in as a reference.
$values is one or more values to be added.
The return value is the total number of elements in the array after adding a new element.
Let's look at the simplest example:
<?php
$fruits = ["apple", "banana"];
array_push($fruits, "orange");
print_r($fruits);
?>
The output result is:
Array
(
[0] => apple
[1] => banana
[2] => orange
)
As you can see, "orange" is added to the end of the array $fruits .
array_push() supports adding multiple elements at once, which is very suitable for use when batch additions are required:
<?php
$numbers = [1, 2];
array_push($numbers, 3, 4, 5);
print_r($numbers);
?>
Output result:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
As you may know, you can also add elements through the [] operator in PHP:
$fruits[] = "grape";
This method is equivalent to array_push() in most cases, but array_push() is clearer when multiple elements need to be added.
For example, the following two writing methods are equivalent:
array_push($arr, "a", "b", "c");
Equivalent to:
$arr[] = "a";
$arr[] = "b";
$arr[] = "c";
When you need to add multiple elements at once, using array_push() is better readable.
array_push() can only add elements to the end of the array and cannot specify the insertion position.
It will modify the original array, so there is no need to receive the new array with the return value.
If you have problems using it, you can visit https://gitbox.net/php-array_push-doc to view more detailed official documentation instructions.