How do I add elements to an array in PHP?

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 length of the array. The "array" parameter refers to the original array to which elements are added. If the first argument is not an array, the function will raise a warning. The parameters "val1, val2" are the elements we want to put in 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.
How do I add elements to an array in PHP? Execute
<?php
$fruits = array("apple", "banana");

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

print_r($fruits);
?>
Updated: Viewed: 844 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