Add elements to an array in PHP
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.
|
1 2 3 4 5 6 7 8 9 10 |
<?php $arr = [1, 2, 3]; $arr[] = 4; echo json_encode($arr); /* Output: [1,2,3,4] */ ?> |
The $array[] = $var syntax made it very convenient to insert a key and value pair into an associative array, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php $arr = ["a" => "apple", "b" => "ball", "c" => "cat"]; $key = "d"; $value = "dog"; $arr[$key] = $value; print_r($arr); /* Output: Array ( [a] => apple [b] => ball [c] => cat [d] => dog ) */ ?> |
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:
|
1 2 3 4 5 6 7 8 9 10 |
<?php $arr = [1, 2, 3]; array_push($arr, 4, 5); echo json_encode($arr); /* Output: [1,2,3,4,5] */ ?> |
That’s all about adding elements to an array in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)