Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding elements to array? [duplicate]

Tags:

arrays

php

How can I add more than one element to my keyed array?

array_add($myArray, 'key', 'a');
array_add($myArray, 'key-2', 'b');

Is there a better way?

like image 454
panthro Avatar asked Jul 19 '26 00:07

panthro


1 Answers

There is no need for any other custom function because in PHP there is a built-in function for this and it's array_merge and you can use it like this:

$myArray = array('one' => 'TheOne', 'two' => 'TheTwo');
$array = array_merge($myArray, array('three' => 'TheThree', 'four' => 'TheFour'));

print_r($array);

Output:

Array
(
    [one] => TheOne
    [two] => TheTwo
    [three] => TheThree
    [four] => TheFour
)

You can also use this:

$myArray1 = array('one' => 'TheOne', 'two' => 'TheTwo');
$myArray2 = array('three' => 'TheThree', 'four' => 'TheFour');;

$array = $myArray1 + $myArray2;
print_r($array);

Output:

Array
(
    [one] => TheOne
    [two] => TheTwo
    [three] => TheThree
    [four] => TheFour
)
like image 196
The Alpha Avatar answered Jul 20 '26 16:07

The Alpha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!