markb
markb

Reputation: 1295

array_merge is not replacing the matching $key

I'm trying to figure out merging two arrays, which was originally working but now I'm trying to merge multidimensional arrays.

First array:

$old_array = 
Array (
    [2] => Array (
        [a] => Location 2
        [b] => loc02
        [c] => Array (  )
    )

    [3] => Array (
        [a] => Location 3
        [b] => loc04
        [c] => Array ( [reader] => reader )
    )
)

And the second array:

$new_array = 
Array (
    [3] => Array (
        [a] => Location 3 New
        [b] => loc06
        [c] => Array ( [publisher] => publisher )
    )
)

When I run then through the array_merge( $old_array, $new_array ) the second array just gets added to the bottom opposed to replacing the same line.

This was working previously, the only change has been adding [c]'s array and not sure if the merge is causing the adding not replacement.

Upvotes: 0

Views: 202

Answers (1)

Naveen Kumar
Naveen Kumar

Reputation: 160

For numeric indices, array_merge will just append the new items to the end of the first array. This works well for string index, as the values gets overwritten. If you want to merge them for numeric indices, use "+" operator.

Check out this comment: https://www.php.net/manual/en/function.array-merge.php#92602

Forgot to add, if you have 2 arrays, $a and $b and you want to overwrite the values of $a with values of $b, then, $new_array = $b + $a; So, the array above would result in:

Array
(
    [3] => Array
        (
            [a] => Location 3 new
            [b] => loc06
            [c] => Array
                (
                    [publisher] => publisher
                )

        )

    [2] => Array
        (
            [a] => Location 2
            [b] => loc02
            [c] => Array
                (
                )

        )

)

Upvotes: 3

Related Questions