In this tutorial, you shall learn about PHP array_push() function which can add one or more elements to an array, with syntax and examples.

PHP array_push() Function

The PHP array_push() function pushes (appends) one or more elements to the end of given array.

PHP array_push() modifies the original array to which we are appending the values.

Syntax of array_push()

The syntax of PHP array_push() function is

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

where

ParameterDescription
array[mandatory] An array to which we append/insert/push values at the end of it.
value1[optional] The value to append to the array.
value2[optional] Another value to append to array at end after value1.
[optional] More values to append to the array.

Function Return Value

PHP array_push() function returns the number of elements in the new updated array appended with values.

ADVERTISEMENT

Examples

1. Push/Append Value to Array

In this example, we will take an array with two values. We will use array_push() function to append a value to this array.

PHP Program

<?php
$array1 = array("apple", "banana");
array_push($array1, "mango");
print_r($array1);
?>

Output

2. Push/Append Multiple Values to Array

In this example, we will push two values to a given array in a single statement using array_push() function.

PHP Program

<?php
$array1 = array("apple", "banana");
array_push($array1, "mango", "orange");
print_r($array1);
?>

Output

3. Print return value of array_push()

In this example, we will examine the return value of array_push() function.

We will take two elements in the array, and push two values to this array. The array must be updated and array_push() must return the new count of values which is four: Two previous values in array and two newly pushed values to array.

PHP Program

<?php
$array1 = array("apple", "banana");
$count = array_push($array1, "mango", "orange");
print_r($count);
?>

Output

Conclusion

In this PHP Tutorial, we learned how to append or push values to an array, using PHP Array array_push() function.