array_push()

Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
Anonymous contributor
Published Jul 8, 2023Updated Sep 5, 2023
Contribute to Docs

The array_push() method adds one or more element values to the end of an array, and returns the updated array.

Syntax

array_push($array, $value1, $value2, ... $valueN)

The array_push() function has one required parameter and some optional parameters:

  • $array: Specifies the input array.
  • $value1 ... $valueN: Specifies the element values to add. This function adds one or more element values at a time which are separated by commas.

The array_push() function returns an array with the added elements.

Example

The following example uses the array_push() function to add "Chevrolet", and "Toyota" element values to the end of the indexed array $car_brands:

<?php
$car_brands = array("Mercedes","Ford");
array_push($car_brands,"Chevrolet","Toyota");
print_r($car_brands);
?>

The example will result in the following output:

Array (
[0] => Mercedes
[1] => Ford
[2] => Chevrolet
[3] => Toyota
)

Codebyte Example

This example is runnable and uses the array_push() function:

Note: The example uses count() to highlight the length of the array before and after the addition of elements. A foreach loop is used to cycle through the keys and values of the array.

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

All contributors

Looking to contribute?

Learn PHP on Codecademy