How to add elements to array in PHP? There are multiple methods to do that. Also, depends on whether your element(s) to be added contains keys or not, different methods could be used.

Quick ways to add elements to array in PHP

There are two quick ways to add new elements to an array in PHP.

1. Use the array_push() function

Assuming we have the $fruits array and we want to add some fruit elements to it:

PHP

Results:

PHP

2. Use bracket method

Use the [] bracket with array variable to add new elements into it:

PHP

This will produce the same result as the array_push() method.

The above examples will add new elements to array in PHP, but with elements without keys. But how do we add new elements with keys to array?

Add elements to array in PHP with keys

To add elements with keys to PHP array so it will become an associative array, we can use the above methods as well, but with slight adjustment:

By array_push() method

PHP

Result:

PHP

By brackets method

PHP

Again, this will show the same result as the array_push() method.

Tips

You can quickly assign your array by declare the elements right into it:

PHP