Current Location: Home> Latest Articles> Basic method of adding elements to PHP array using array_push

Basic method of adding elements to PHP array using array_push

gitbox 2025-06-03

1. What is array_push() ?

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.

2. Basic usage examples

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 .

3. Add multiple elements

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
)

4. Comparison with [] operator

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.

5. Things to note

  1. array_push() can only add elements to the end of the array and cannot specify the insertion position.

  2. It will modify the original array, so there is no need to receive the new array with the return value.

  3. If you have problems using it, you can visit https://gitbox.net/php-array_push-doc to view more detailed official documentation instructions.