1

I have two arrays. The one's array key is another's value. Here is code:

$arr1 = array(
    'a' => 'apple',
    'b' => 'banana',
    'c' => 'pear',
);

$arr2 = array(
    'bird' => 'a',
    'dog' => 'b',
);

And my question, how to combine two arrays in one like:

$arr3 = array(
    'bird' => 'apple',
    'dog' => 'banana',
);

Is there have some array function to do this probably?

1
  • just loop the $arr2 values into the keys of $arr1 using foreach, $arr1[$value_from_$arr2] no need for special functions Commented Oct 27, 2015 at 2:48

2 Answers 2

1
<?php
$arr3 = array();

foreach ($arr2 as $item => $value) {
  $arr3[$item] = $arr1[$value];
}
print_r($arr3);

something along those lines anyway.

If you literally want to merge the arrays, array_merge will do the job fine.

Sign up to request clarification or add additional context in comments.

Comments

1

Edit: This is a fun way and matches the keys:

$arr3 = array_combine(array_intersect_key($k = array_flip($arr2), $arr1),
                      array_intersect_key($arr1, $k));

Original with no key matching:

Here's a way. Doesn't matter which array is longer:

$arr3 = array_combine(array_slice(array_keys($arr2), 0, count($arr1)),
                      array_slice($arr1, 0, count($arr2)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.