How to add element to array PHP
How to add element to array PHP
If you are a programmer, you will need to work with arrays at some point, arrays are something referred to like a collection of elements. It is much easier to have an array with n number of elements, instead of having n number of variables.
Problem
Lets say you initialized the array, or declare it, and you want to add some elements to your array.
1st solution
First solution to this is by assigning to your array variable the parentheses [], this will make it so the server will interpret the code as to add the new element to a new array key in our array. This is the fastest solution I believe.
1 2 3 4 5 6 7 |
//array declaration $myArray = array(); //proceed the adding $myArray[] = 5; $myArray[] = "just a string"; $myArray[] = 14123; |
2nd solution
Second solution is by using the array_push function, the difference here is that you only specify the array variable and, separated by commas, you can add multiple elements, for example:
1 2 3 |
$myArray = array(); array_push($myArray, 5); array_push($myArray, 14123, 'another element'); |
3rd solution (for associative arrays)
The 3rd solution is mostly used in loops where you are adding associative elements to your associative array, although it can be used outside loops when you are adding only one element.
1 |
$myArray['key'] = 'test'; |
The key in this solution can be anything you need, for example
1 2 |
$myArray['cat'] = 'thomas'; $myArray['dog'] = 'alpo'; |
As stated in the PHP documentation, if you’re only pushing a single element every time or a single element once, it is better to use the $myArray[] = 5 method not only because it’s less characters to do the same operation, but it also doesn’t impose the performance overhead of a function call, which array_push() would.