In this article, we will explore different methods to append to an array in PHP.
Append to an Array in PHP
Three methods exist to append to an array in PHP:
Method 1: Using [] Operator
In PHP, simply using square brackets [] is an easy method to append a new element to an existing array. The first step is to declare the array with one or more initial elements. After that, you can use the [] operator with the array variable and the element you want to add.
The following example uses the [] operator to append to an array in PHP:
The above code initializes an array $emArray with four integer values and then appends a new integer value 2 to the end of the array using the [] operator. Finally, the print_r() function is used to display the modified array $emArray.
Output
Method 2: Using array_push() Function
The array_push() function is a built-in function in PHP that makes it easy for you to append to an array. It takes two or more arguments. The first one is the array to which the user wants to add elements and the other arguments should be the elements that the user wants to add to the array.
The following example shows the illustration of the array_push() function in PHP:
The above code uses the array_push() function to append the element “2” to the end of the $emArray array. The print_r() function is then used to display the updated array.
Output
3: Using array_merg() Function
You can also use another built-in function array_merg() in PHP to easily append elements to an existing array. It can be done by first defining an array and then using the array_merg() function to append an element to an array.
The following example uses the array_merg() function to append to an array in PHP:
$emArray = array(5, 6, 10, 14);
$emArray = array_merge($emArray, array(2,5,7));
print_r($emArray);
?>
The above code uses the array_merge() function to merge the $emArray array with another array containing three elements. Finally, it updates the array and displays using the print_r() function.
Output
Conclusion
In PHP, arrays are important for keeping different types of data in one place. When we need to add more data to an already existing array, we have different ways to do it. We can use the square bracket notation [], which is simple and easy to use. We can also use two built-in PHP functions called array_push() and array_merge(), which give us more options to add data.