How to Push an Element to an Array in PHP?

Last updated on February 13, 2023

The array_push() is a built-in function that pushes elements into the array. It accepts the first parameter as an array in which a new element has to be added and in the second parameter it accepts a value or element that becomes part of the array.

Let’s create a variable that stores an array containing favorite countries.

$favoriteCountries = array("Germany","United Kingdom");

It has only two countries, to add more countries to the array we can use the array_push() function.

array_push($favoriteCountries, "South Korea", "Vietnam");

Here we passed the variable that stores the favorites countries array into the array_push() function as the first argument and two countries as the second and third arguments.

The array_push() function pushes the second and third arguments into the favorite countries array. To see the result we can use the print_r() function that prints the array.

// Output: 
    [0] => Germany
    [1] => United Kingdom
    [2] => South Korea
    [3] => Vietnam

Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: PHP, PHP-Functions,