How to Add New Elements  to an Array in PHP
  John Mwaniki /   04 Dec 2023

How to Add New Elements to an Array in PHP

Arrays play an important role in programming, serving as data structures that store collections of values.

After creating an array, there are instances where dynamically adding elements to it becomes a necessity.

For example, if you have an E-commerce website, you usually manage the shopping cart using arrays. As users add items to their cart, you dynamically add the new item's details to the array as a separate element.

In this article, I will show you how to add new elements to an array in PHP with the help of multiple examples for a better understanding.

Techniques for Adding Elements to an Array

There exist several ways in which you can add elements to arrays in PHP, each with its advantages and context:

1. Using Square Bracket Notation

This is the simplest and most basic way to add elements to an array. It appends elements to the end of an existing array.

Example 1

// Existing array
$colors = ['red', 'green'];

echo "Array before:<br>";
print_r($colors);

// Adding a new color to the array
$colors[] = 'blue';

echo "<br>Array after:<br>";
print_r($colors);

Output:
Array before:
Array ( [0] => red [1] => green )
Array after:
Array ( [0] => red [1] => green [2] => blue )

Example 2

You can also directly assign elements to specific indexes within the square bracket, i.e., if an array has two elements, by adding the third you will be introducing array index 2. So you can directly assign a value to index 2.

// Existing array
$fruits = ['apple', 'banana'];

echo "Array before:<br>";
print_r($fruits);

// Add a new fruit (mango) at index 2
$fruits[2] = 'mango';

echo "<br>Array after:<br>";
print_r($fruits);

Output:
Array before:
Array ( [0] => apple [1] => banana )
Array after:
Array ( [0] => apple [1] => banana [2] => mango )

Example 3

You can also add a new element to an associative array using the square brackets notation. This is the same as example 2 above, only that instead of specifying a numeric index in the brackets, you use the key of the key-value pair, i.e, $array[key] = value.

// Existing array
$user = array("name" => "John Doe", "age" => 30, "gender" => "Male");

echo "Array before:<br>";
print_r($user);

// Add an email key-value pair to the array
$user['email'] = 'johndoe@email.com';

echo "<br>Array after:<br>";
print_r($user);

Output:
Array before:
Array ( [name] => John Doe [age] => 30 [gender] => Male )
Array after:
Array ( [name] => John Doe [age] => 30 [gender] => Male [email] => johndoe@email.com )

2. Using the array_push() Function

The array_push() is a built-in function in PHP for adding one or more elements to the end of an array. It's ideal for adding multiple elements without specifying indexes.

Syntax

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

The first parameter specifies the array to which you want to add elements while the other parameter(s) specifies the values for the new elements.

Example

// Existing array
$laptops = array('apple', 'hp', 'lenovo');

echo "Array before:<br>";
print_r($laptops);

// Adding "asus" and "dell" to the end of array
array_push($laptops, 'asus', 'dell');

echo "<br>Array after:<br>";
print_r($laptops);

Output:
Array before:
Array ( [0] => apple [1] => hp [2] => lenovo )
Array after:
Array ( [0] => apple [1] => hp [2] => lenovo [3] => asus [4] => dell )

3. Using the array_unshift() Function

Contrary to array_push, the array_unshift() function adds elements at the beginning of an existing array. This can be useful for prioritizing specific data when adding it to an array.

Example

// Existing array
$colors = array('white', 'purple', 'yellow');

echo "Array before:<br>";
print_r($colors);

// Adding "red", "green" and "blue" to the beginning of array
array_unshift($colors, 'red', 'green', 'blue');

echo "<br>Array after:<br>";
print_r($colors);

Output:
Array before:
Array ( [0] => white [1] => purple [2] => yellow )
Array after:
Array ( [0] => red [1] => green [2] => blue [3] => white [4] => purple [5] => yellow )

4. Using the array_merge() Function

The array_merge() function merges the elements of one or more arrays so that the values of one are appended to the end of the previous one.

Syntax

array_merge(array1, array2, ...)

It accepts one or more arrays as parameters and returns the resulting array after merging.

Example 2

// Existing array
$colors = ['orange', 'purple', 'yellow'];

echo "Array before:<br>";
print_r($colors);

// New colors array
$newcolors = ['green', 'black'];

$result = array_merge($colors, $newcolors);

echo "<br>Array after:<br>";
print_r($result);

Output:
Array before:
Array ( [0] => orange [1] => purple [2] => yellow )
Array after:
Array ( [0] => orange [1] => purple [2] => yellow [3] => green [4] => black )

As opposed to the square brackets notation that we covered earlier, the array_merge() function allows you to add multiple key-value pairs to an associative array at once.

Example 2

// Existing array
$user = array("name" => "Frodo", "age" => 35);

echo "Array before:<br>";
print_r($user);

$newarray = array("gender" => "Male", "email" => "frodo@email.com");

// Add adding key-value pair(s) to the array
$result = array_merge($user, $newarray);

echo "<br>Array after:<br>";
print_r($result);

Output:
Array before:
Array ( [name] => Frodo [age] => 35 )
Array after:
Array ( [name] => Frodo [age] => 35 [gender] => Male [email] => frodo@email.com )

Adding Arrays as Elements to Arrays

In all the examples we have covered above, I have shown you how to add strings or numbers as new elements to arrays. But it's also possible to add arrays as values of new elements to existing multi-dimensional arrays.

For example, let's say you have a database table (users) for storing user details. It has multiple rows, each comprising multiple details about the user such as name, email, gender, age, etc.

MySQL database table with user details

If you want to fetch all this data and organize it in an array, you will need to have each record as an individual array and then an array comprising of all these arrays.

Example 1

Adding associative arrays of database records as elements to an array using the square bracket notation.

// Establishing a database connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Creating an empty array
$users = array();

// Selecting all records from the table
$query = "SELECT * FROM users";

// Executing the SQL query
$result = mysqli_query($conn, $query);

// Looping through rows and adding them to the array
while ($row = mysqli_fetch_assoc($result)) {
    $users[] = $row;
}

// Closing database connection
mysqli_close($conn);

// Printing the array
print_r($users);

Output:
Array (
   [0] => Array (
         [id] => 1
         [name] => John
         [email] => john@gmail.com
         [gender] => Male
         [age] => 30
   )
   [1] => Array (
         [id] => 2
         [name] => Muhamad
         [email] => muhamad@gmail.com
         [gender] => Male
         [age] => 35
   )
   [2] => Array (
         [id] => 3
         [name] => Jane
         [email] => jane@gmail.com
         [gender] => Female
         [age] => 27
   )
   [3] => Array (
         [id] => 4
         [name] => Rajesh
         [email] => rajesh@yahoo.com
         [gender] => Male
         [age] => 25
   )
   [4] => Array (
         [id] => 5
         [name] => Philip
         [email] => philip@email.com
         [gender] => Male
         [age] => 32
   )
)

In the above example, we created an empty array and named it $users. We then selected all the records from the users' table. Lastly, we added all these records as associative arrays to the $users array, each at a time via a while loop then printed the resulting multi-dimensional array.

Alternatively, you can use array_push($users, $row) in the place of $users[] = $row in the example above and the output will be the same.

That's all for this article.

I hope that by going through this article, you can now confidently add new elements to an array in PHP. Choose the method that best suits your specific needs.