How to add element to array PHP

→ Are you a new visitor? Please visit the page guidance for new visitors ←

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.

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:

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.

The key in this solution can be anything you need, for example

Heads up! Keep in mind that if you assign an element with a key that already exists, it will replace the existing value with the new one.

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.

Request an article ←