Anusha
Anusha

Reputation: 673

Merge two associative arrays sharing keys and concatenate string values

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?

Upvotes: 1

Views: 878

Answers (2)

LF-DevJourney
LF-DevJourney

Reputation: 28529

try this:

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

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

$o = [];
foreach($arr1 as $k => $v)
{
    $o[$k][] = $v;
}
foreach($arr2 as $k => $v)
{
    $o[$k][] = $v;
}
$result = array_map(function($v){implode(',', array_unique($v));}, $o);

Upvotes: 2

Thamilhan
Thamilhan

Reputation: 13313

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

Upvotes: 2

Related Questions