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/*from  ww w .j  ava2s. com*/
$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/*from   w  ww  . java 2s .com*/
$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//from  ww w  .java 2s  . c  o  m
$authors = array( "Java", "PHP", "CSS", "HTML" ); 
echo array_push( $authors, "Javascript", "Python" ) . "\n";

print_r( $authors );   
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions