In this post, we will see how to add elements to an array in PHP.

1. Using $array[] = $var syntax

A fairly simple and common approach is to add elements to an array is using the $array[] = $var syntax. This is a recommended approach to add a single element to the array to avoid the overhead of calling a function. It pushes the specified value to the end of the array.

Download  Run Code

 
The $array[] = $var syntax made it very convenient to insert a key and value pair into an associative array, as shown below:

Download  Run Code

2. Using array_push() function

The standard and recommended approach to add multiple elements to an array is using the array_push() function. It has basically the same effect as $array[] = $var for each passed value.

Following is a simple example demonstrating this:

Download  Run Code

That’s all about adding elements to an array in PHP.