Pushing an Element into a PHP Array

To add elements to a PHP array, you can use the array_push($array, $val1, $val2, ....) function. The array_push() function adds one or more elements to the end of the array and automatically increases the array's length. The $array parameter refers to the original array to which elements are added. The function will raise an exception if the first argument is not an array. The parameters $val1 and $val2 are the elements we want to push into the array. In this PHP Push Elements to Array example, we add elements to an array using the array_push() function. Click Execute to run the PHP Array Push Example online and see the result.
Pushing an Element into a PHP Array Execute
<?php
$fruits = array("apple", "banana");

array_push($fruits, "mango", "orange");

print_r($fruits);
?>
Updated: Viewed: 1423 times

PHP Array Push Syntax

The following is the syntax of the array_push() function, which inserts one or more elements at the end of an array:

PHP array_push() Syntax
array_push(array, val1, val2, ...)

Where:
  • array: defines an input array
  • val (Optional): one or more elements that we want to put in the array. In the syntax above, the list looks like this: $val1, $val2, ….
PHP array_push() Example
<?php
$fruits = array("apple", "banana");

array_push($fruits, "mango", "orange");

print_r($fruits);
?>

#output: Array
(
    [0] => apple
    [1] => banana
    [2] => mango
    [3] => orange
)

See also