Thursday, 30 August 2018

merge two associative arrays with the same key

I have two arrays:

$arr1 = array("123" => "abc");

$arr2 = array("123" => "xyz", "456" => "lmn");

I want the resultant array to be :
$arr = array("123" => "abc,xyz", "456" => "lmn");
I know I can write some code to fetch the values corresponding to keys and then concat with a separator like ';' or ',', but I want to know is there any efficient way to do this? An in-built function maybe?
Thanks in advance!

Simple foreach will do! Check inline comments
$arr1 = ["123" => "abc"];

$arr2 = ["123" => "xyz", "456" => "lmn"];

foreach ($arr2 as $key => $value) {
    if(array_key_exists($key, $arr1)) // Check if key exists in array
        $arr1[$key] .= ",$value";     // If so, append
    else
        $arr1[$key] = $value;         // otherwise, add
}

print_r($arr1);

Prints
Array
(
    [123] => abc,xyz
    [456] => lmn
)

Check this Eval

0 comments:

Post a Comment