PHP array_push PHP array push

How to use PHP array_push with examples

The PHP array_push function adds elements to the end of an array. This function based on its name push elements to the end of an array in PHP (PHP array push).

You could insert one or more values to the array by the array_push function.

It is categorized under the PHP array functions. Read more about PHP Array in our tutorial.

PHP array_push function syntax

array_push(array, value1, value2, ...);

With this function, you can add one value or more values to a given array’s end.

arrayRequiredIt is an array that you want to add elements to it.
value1RequiredIt is the value that you want to add. This value can be any data.
value2OptionalIt is the value that you want to add. This value can be any data.
Returned valueReturns the new number of elements in the array

PHP array_push() function must have at least two arguments one is the array and the other is a value. But in PHP version 7.3.0 this function can be called with only one parameter.

PHP array push function is available in PHP since version 4.

The length of the array increases by the number of variables you pushed.

Add elements to an array in PHP with array_push

$cars = array('Ferrari', 'Benz', 'BMW');
array_push($cars, 'Volvo', 'Toyota');

var_dump($cars);

Output:

array (size=5)
  0 => string 'Ferrari' (length=7)
  1 => string 'Benz' (length=4)
  2 => string 'BMW' (length=3)
  3 => string 'Volvo' (length=5)
  4 => string 'Toyota' (length=6)

This function appends values with indexed keys (numeric keys) even if your array is an associative array.

$cars = array('fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW');
array_push($cars, 'Volvo', 'Toyota');

var_dump($cars);

Output:

array (size=5)
  'fer' => string 'Ferrari' (length=7)
  'ben' => string 'Benz' (length=4)
  'bmw' => string 'BMW' (length=3)
  0 => string 'Volvo' (length=5)
  1 => string 'Toyota' (length=6)

If you want to add only one value to the array it is better to add that with [] and don’t use the array_map function.

$cars = array('fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW');
$cars['vol'] = 'Volvo';

var_dump($cars);

Output:

array (size=4)
  'fer' => string 'Ferrari' (length=7)
  'ben' => string 'Benz' (length=4)
  'bmw' => string 'BMW' (length=3)
  'vol' => string 'Volvo' (length=5)

How to push value and key into PHP array

There is no way you could add an associative array to another with the array_push function. It is better to use [] to add elements as we mentioned in this tutorial or use other methods.

Shopping Cart