Array Functions
Advertisements

PHP array_push() Function

Topic: PHP Array ReferencePrev|Next

Description

The array_push() function inserts one or more elements at the end of an array.

The following table summarizes the technical details of this function.

Return Value: Returns the new number of elements in the array.
Changelog: Since PHP 7.3.0, this function can now be called with only one parameter (i.e. array). Earlier, at least two parameters have been required.
Version: PHP 4+

Syntax

The basic syntax of the array_push() function is given with:

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

The following example shows the array_push() function in action.

<?php
// Sample array
$colors = array("red", "green", "blue");
    
// Pushing values to the array
array_push($colors, "yellow", "orange");
print_r($colors);
?>

Parameters

The array_push() function accepts the following parameters.

Parameter Description
array Required. Specifies the array to work on.
value1, value2, ... Optional. Specifies the values to push onto the end of the array.

More Examples

Here're some more examples showing how array_push() function actually works:

You can also push elements to the associative array. However, in that case, PHP automatically assigns a numeric key to those values. Let's check out the following example:

<?php
// Sample array
$alphabets = array("a"=>"apple", "b"=>"ball", "c"=>"cat");
    
// Pushing values to the array
array_push($alphabets, "dog", "elephant");
print_r($alphabets);
?>
Advertisements
Bootstrap UI Design Templates