7

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?

0

3 Answers 3

9

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
)
Sign up to request clarification or add additional context in comments.

Comments

5

I prefer:

$myArray['key'] = 'a';
$myArray['key-2'] = 'b';

But this is not really better, because you're not adding more than one in a single command.

And if you really need to add multiple, you can always create a helper:

function array_add_multiple($array, $items)
{
    foreach($items as $key => $value)   
    {
        $array = array_add($items, $key, $value);
    }

    return $array;
}

And use it as

$array = array_add_multiple($array, ['key' => 'a', 'key-2' => 'b']);

or, if you're not using PHP 5.4:

$array = array_add_multiple($array, array('key' => 'a', 'key-2' => 'b'));

Comments

1

My custom "on the fly" method:

function add_to_array($key_value)
    {
        $arr = [];
        foreach ($key_value as $key => $value) {
            $arr[] = [$key=>$value];
        }
        return $arr;
    }
    dd(add_to_array(["hello"=>"from this array","and"=>"one more   time","what"=>"do you think?"]));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.