PHP Tutorial - PHP array_push() function






Syntax

PHP array_push() function has the following syntax.

int array_push ( array &arr, mixed var [, mixed ...] )

Definition

The array_push() function pushes value onto the end of an array. This is the opposite of the array_pop() function:

Parameter

ParameterIs RequiredDescription
arrayRequired.Array to push
value1Required.Value to add
value2Optional.Value to add

Note

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.





Note 2

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.





Example 1

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.

Example 2

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.