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:
$fruits = array();
// One element per time
array_push($fruits, 'orange');
array_push($fruits, 'apple');
array_push($fruits, 'banana');
// Or multiple elements
array_push($fruits, 'orange', 'apple', 'banana');
Results:
// print_r($fruits)
Array
(
[0] => orange
[1] => apple
[2] => banana
)
2. Use bracket method
Use the []
bracket with array variable to add new elements into it:
$fruits = array();
$fruits[] = 'orange';
$fruits[] = 'apple';
$fruits[] = 'banana';
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
$fruits = array();
// Element as array with key
array_push($fruits, array('apple' => 'red', 'banana' => 'yellow'));
// Same way but with shorthand syntax
array_push($fruits, ['orange' => 'red', 'banana' => 'yellow']);
Result:
// print_r($fruits);
Array
(
[0] => Array
(
[apple] => red
[banana] => yellow
)
)
print_r($fruits['apple']); // red
print_r($fruits['banana']); // yellow
By brackets method
$fruits = array();
// Element as array with key
$fruits[] = array('apple' => 'red', 'banana' => 'yellow');
// Same way but with shorthand syntax
$fruits[] = ['orange' => 'red', 'banana' => 'yellow'];
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:
// New empty array
$fruits = [];
// Declare array with elements
$fruits[] = ['apple', 'orange'];
You might be interested in…
References
External: See the array_push()
function on official PHP Manual.