0

Assuming I don't want to loop through and build a new array, is there a built in way in PHP to add two arrays together and push all keys from the second array after the keys from the first? I Googled around and couldn't find anything that does exactly this, but wondering if anyone might know

For example to combine these..

array( 0 => "a", 1 => "b" );
array ( 0 => "c", 1 => "d" );

and get this..

array( 0 => "a", 1 => "b", 2 => "c", 3 => "d" );

3 Answers 3

4

This:

array_merge(array( 0 => "a", 1 => "b" ),array ( 0 => "c", 1 => "d" ));

Or

array( 0 => "a", 1 => "b" ) + array ( 0 => "c", 1 => "d" )

This first one will overwrite duplicate keys, the second will not. And you may have to sort the array afterwords.

Or, you could do:

array_merge(array_values(array( 0 => "a", 1 => "b" )), array_values(array ( 0 => "c", 1 => "d" )))

That will definitely work

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks dave, I actually looked at array_merge, looks like I just didn't pay close attention to the documentation.. doh!
Please note though, "overwrite duplicate keys" only applies to non-numeric keys. numeric keys are appended.
1

Take a look at array_merge.

<?php
$ab = array('a', 'b');
$cd = array('c', 'd');

var_dump(
    array_merge($ab, $cd)
);

/*
    array(4) {
      [0]=>
      string(1) "a"
      [1]=>
      string(1) "b"
      [2]=>
      string(1) "c"
      [3]=>
      string(1) "d"
    }
*/

Comments

0

You could also try:

<?php
    $array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
    $array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
    $result = array_merge($array1, $array2);

    print_r($result);

    /*
    Array
    (
        [0] => zero_a
        [1] => two_a
        [2] => three_a
        [3] => one_b
        [4] => three_b
        [5] => four_b
    )
    */
?>

Reference

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.