-1

In PHP there is two array:

$x = array( "a" => "0123", "b" => "1234", "c" => "0123");
$y = array( "a" => "3210", "b" => "1234", "d" => "0123");

i wish to get the result in one array like this:

// right
Array
(
[a] => 0123
[b] => 1234
[c] => 0123
[a] => 3210
[d] => 0123
)

I tried with array_merge($x, $y):

// wrong    
Array
(
[a] => 3210
[b] => 1234
[c] => 0123
)

It happen cause there is old database and new database, i am getting both value from both database. If value from both database ist exactly equal, then it needed only on value like this:

[b] => 1234

Please is there some solution in PHP-Code?

4
  • 6
    You can't have 2 indexes with the same name (a in this case) as stated => [a] => 0123 [b] => 1234 [c] => 0123 [a] => 3210 [d] => 0123 And array_merge gives this result (with the d ) => ["a"]=> string(4) "3210" ["b"]=> string(4) "1234" ["c"]=> string(4) "0123" ["d"]=> string(4) "0123" Commented May 23, 2018 at 10:50
  • 2
    Possible duplicate of Merging arrays with the same keys Commented May 23, 2018 at 10:56
  • 1
    This won't happen, key name in an array is unique, it impossible you have two key named 'a' in an array. Commented May 23, 2018 at 10:57
  • 1
    if the key 'a' repeat two time with different values, then consider 'a'=>value1, value2], this way you can have both different values Commented May 23, 2018 at 10:59

2 Answers 2

2

Becuase of you cant get same keys use array_merge_recursive. It will make muldimensional arrays for same keys.

$ar1 = array("color" => array("favorite" => "red"), 5);

$ar2 = array(10, "color" => array("favorite" => "green", "blue"));

$result = array_merge_recursive($ar1, $ar2);
[color] => Array
    (
        [favorite] => Array
            (
                [0] => red
                [1] => green
            )

        [0] => blue
    )

[0] => 5
[1] => 10
Sign up to request clarification or add additional context in comments.

1 Comment

You could use the OP's actual data, might be more expresive
0

Arrays cannot have duplicate keys, if keeping the keys isn't important to you then the following would work fine:

This code is pulled straight from the PHP array_merge documentation.

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

Outputs:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

Also see: array merge with duplicates php

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.