PHP array_push() function has the following syntax.
int array_push ( array &arr, mixed var [, mixed ...] )
The array_push()
function pushes value onto the end of an array.
This is the opposite of the array_pop()
function:
Parameter | Is Required | Description |
---|---|---|
array | Required. | Array to push |
value1 | Required. | Value to add |
value2 | Optional. | Value to add |
To add an element to the end of an array, we can use the square bracket syntax.
Or we can use array_push(), which allows us to add multiple elements at once and also tells us the new length of the array.
With both array_unshift() and array_push(), if you include an array as one of the values to add, the array is added to the original array as an element, and the original array become a multidimensional array:
<?PHP
$authors = array( "Java", "PHP", "CSS", "HTML" );
$newAuthors = array( "Javascript", "Python" );
echo array_push( $authors, $newAuthors ) . "\n";
print_r( $authors );
?>
If you instead want to add the elements of the array individually to the original array, use array_merge().
The code above generates the following result.
Push element to an array
<?PHP
$firstname = "java2s.com";
$names = array("PHP", "Java", "C#", "HTML", "CSS");
array_push($names, $firstname);
print_r($names);
?>
The code above generates the following result.
You use array_push in much the same way as array_unshift(): pass the array, followed by the value(s) to add.
<?PHP
$authors = array( "Java", "PHP", "CSS", "HTML" );
echo array_push( $authors, "Javascript", "Python" ) . "\n";
print_r( $authors );
?>
The code above generates the following result.