Carol.Kar
Carol.Kar

Reputation: 5355

array_merge removes my duplicates

I am adding several arrays to a $result array.

Find below my example what I am currently doing:

$res = array();

$arr1 = array("key1" => array("10","12"));
$arr2 = array("key2" => array("1","11"));
$arr3 = array("key1" => array("10","12"));
$arr4 = array("key2" => array("1","11"));

$res = array_merge($res, $arr1);
$res = array_merge($res, $arr2);
$res = array_merge($res, $arr3);
$res = array_merge($res, $arr4);

print_r($res);

// OUTPUT:
// #######
Array
(
    [key1] => Array
        (
            [0] => 10
            [1] => 12
        )

    [key2] => Array
        (
            [0] => 1
            [1] => 11
        )

)

However, I would like to have the following output:

Array
(
    [key1] => Array
        (
            [0] => 10
            [1] => 12
        )

    [key2] => Array
        (
            [0] => 1
            [1] => 11
        )
    [key1] => Array
        (
            [0] => 10
            [1] => 12
        )

    [key2] => Array
        (
            [0] => 1
            [1] => 11
        )

)

As you can see I would like to add the duplicated arrays to my result array.

Any suggestions why array_merge replaces the duplicated merges and how to turn this behavior of?

I appreciate your replies!

Upvotes: 0

Views: 48

Answers (2)

Spoody
Spoody

Reputation: 2882

This was meant to be a comment but ended up being too long.

You need to understand how arrays work, this is just a brief small explanation. Let's say you have an array:

$array = array(
    'key1' => 'Hello ',
    'key2' => 'World',
    'key1' => 'Foo ',
    'key2' => 'Bar',
);

Now we try to use it like this:

echo $array['key1'].$array['key2'];

If we can use identical keys, which one will be printed? Hello world or Foo bar? or a mix?

The real output is Foo bar because the last two will overwrite the first ones.

Here is a more detailed (and advanced) article explaining how PHP handles arrays.

Upvotes: 2

gview
gview

Reputation: 15381

As commented the answer is no. A key is inherently unique. PHP uses the key to locate the associated value.

You can not accomplish the structure you want, but if all you want is to have all the values in one array structure you could accomplish that simply with this code:

$res = array();

$res[] = array("key1" => array("10","12"));
$res[] = array("key2" => array("1","11"));
$res[] = array("key1" => array("10","12"));
$res[] = array("key2" => array("1","11"));

var_dump($res);
// You'll see all your arrays in one structure

Upvotes: 3

Related Questions