McClaudLive
McClaudLive

Reputation: 53

Combining values from two arrays with same keys

I have two arrays like this:

$arr1 = Array ( [1] => ab [2] => cd [at] => ef )
$arr2 = Array ( [1] => gh [2] => ij [at] => kl )

I want to combine these two arrays to this array:

$arr3 = Array ( [1] => ab-gh [2] => cd-ij [at] => ef-kl )

The keys are the same in the two arrays so I imagine that it is possible to join the values of the arrays with a "-" between like above.

I have googled and tried almost anything (merge, combine, join) but I can't figure it out. Any suggestions?

Upvotes: 1

Views: 10001

Answers (3)

sevavietl
sevavietl

Reputation: 3802

Although accepted answer is perfectly ok, here is a more general solution, that can be used for any number of arrays:

$arr1 = [1 => 'ab', 2 => 'cd', 'at' => 'ef'];
$arr2 = [1 => 'gh', 2 => 'ij', 'at' => 'kl'];
$arr3 = [1 => 'mn', 2 => 'op', 'at' => 'qr'];

$arr = [$arr1, $arr2, $arr3];

$keys = array_intersect(...array_map('array_keys', $arr));

$result = array_combine($keys, array_map(function ($key) use ($arr) {
    return implode('-', array_column($arr, $key));
}, $keys));

Here is the demo.

Upvotes: 1

BERNARDO
BERNARDO

Reputation: 219

Let's say you've got two arrays with the same amount of values and the same keys.

This should help:

$arr1 = Array ("ab", "cd", "at" => "ef");
$arr2 = Array ("gh", "ij", "at" => "kl");
$combinedArray = array();

function combineValues(array $array1, array $array2)
{
    $array3 = array();
    foreach($array1 as $key => $value)
    {
         $array3[$key] = $value . "-" . $array2[$key];
    }

    return $array3;
}

$combinedArray = combineValues($arr1, $arr2);

I really hope this helps.

Regards.

Upvotes: 1

Aurel Bílý
Aurel Bílý

Reputation: 7963

If you can guarantee these two arrays will always have the same keys:

$arr3 = array();
foreach ($arr1 as $key => $val1) {
  $val2 = $arr2[$key];
  $arr3[$key] = $val1 . "-" . $val2;
}

Now, assuming the two have different keys and you want to do a "joined" array with only the keys that exist in both arrays:

$arr3 = array();
foreach (array_intersect(array_keys($arr1), array_keys($arr2)) as $key) {
  $arr3[$key] = $arr1[$key] . "-" . $arr2[$key];
}

This is similar to a SQL inner join.

If you want to do a "joined" array with the keys in either of the arrays, hyphen-joining only the ones that exist in both:

$arr3 = array();
foreach (array_merge(array_keys($arr1), array_keys($arr2)) as $key) {
  if (isset($arr1[$key]) && isset($arr2[$key])) {
    $arr3[$key] = $arr1[$key] . "-" . $arr2[$key];
  } else {
    $arr3[$key] = (isset($arr1[$key]) ? $arr1[$key] : $arr2[$key]);
  }
}

This is similar to a SQL outer join.

Try all of the above online!

Upvotes: 6

Related Questions