2


I want to have an array that contains a list of something, then I have another array that contains a list of something. I want to add those arrays up to each other.
For example, I have this

<?php
$greetings1 = array (
      'a' => 'hello',
      'b' => 'hi'
      );
$greetings2 = array ('c' => 'hey',
      'd' => 'greetings'
     );
array_push($greetings1, $greetings2);

foreach($greetings1 as $a => $b) {
 echo $a.' and '.$b."<br/>";
}
?>

I want it so that the output is:

a and hello
b and hi
c and hey
d and greetings

the real output of the php code above is:

a and hello
b and hi
0 and Array

So how do I properly add the two arrays up?
Thanks!

3 Answers 3

6

You can array_merge

<?php
$greetings1 = array(
    'a' => 'hello',
    'b' => 'hi',
);
$greetings2 = array(
    'c' => 'hey',
    'd' => 'greetings',
);

$greetings = array_merge($greetings1, $greetings2);

Which will output:

Array
(
    [a] => hello
    [b] => hi
    [c] => hey
    [d] => greetings
)
Sign up to request clarification or add additional context in comments.

Comments

3
array_merge($greetings1, $greetings2);

array_push just adds an element at the end of the array (in that case another array).

Comments

1

You're looking for array_merge

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.