How to add elements to an array in PHP?

This tutorial will discuss about unique ways to add elements to an array in php.

Add an element at the end of an Array in PHP

To add an element at the end of array, we can simply apply the script operator (i.e. [] operator) to the array, and assign a value into it. Like this,

$cities[] = "Houston";

It will add the array element at the end of the array.

In the belowe example, we have an array of city names, and we will add a value “Houston” into the array.

Let’s see the complete example,

<?php
// Define an array of city names
$cities = array("New York", "Los Angeles", "Chicago");

// Add an element to the end of the array using the [] operator
$cities[] = "Houston";

// Output the modified array using foreach
foreach ($cities as $city) {
    echo $city . ", ";
}
?>

Output

New York, Los Angeles, Chicago, Houston, 

Add multiple elements to an Array in PHP

The array_push() function in PHP, accepts an array as a first argument, and after that we can pass multiple values in it.

array_push($array_obj, value1, value2, value3)

It will add these values at the end of the array.

In the belowe example, we are going to call the array_push() function to add one element at the end of the array.

Let’s see the complete example,

<?php
// Define an array of city names
$cities = array("New York", "Los Angeles", "Chicago");

// Add an element to the end of the array using array_push()
array_push($cities, "Houston", "Seatle");

// Output the modified array using foreach
foreach ($cities as $city) {
    echo $city . ", ";
}
?>

Output

New York, Los Angeles, Chicago, Houston, Seatle, 

Add element at the front of the array in PHP

We can use the array_unshift() function to add an element at the start of the array.

The array_unshift() function accepts an array as the first argument, and multiple values as other arguments. Then it add these values at the start of the array.

In the below example, we are going to add a value at the front of array in PHP.

Let’s see the complete example,

<?php
// Define an array of city names
$cities = array("New York", "Los Angeles", "Chicago");

// Add an element to the beginning of the array using array_unshift()
array_unshift($cities, "Houston");

// Output the modified array using foreach
foreach ($cities as $city) {
    echo $city . ", ";
}
?>

Output

Houston, New York, Los Angeles, Chicago, 

Summary

We learned how to add an element in an array in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top