combine two maps in php

To combine/merge two maps in PHP, you can use array union operator (+), which returns a new array containing all the elements from both arrays, with the values of the second array overwriting the values of the first array for any matching keys:

main.php
$map1 = ["key1" => "value1", "key2" => "value2"];
$map2 = ["key2" => "new_value2", "key3" => "value3"];

$merged_map = $map1 + $map2;

print_r($merged_map);
157 chars
7 lines

The output will be:

main.php
Array (
    [key1] => value1
    [key2] => value2
    [key3] => value3
)
73 chars
6 lines

As you can see, the "key2" value in $map2 overwrote the "key2" value in $map1.

related categories

gistlibby LogSnag