1
$arrayA = Array ( 
                 [0] => 1, 
                 [1] => 2, 
                 [2] => 4 
                )

$arrayB = Array ( 
                 [1] => Dog, 
                 [2] => Cat, 
                 [3] => Cow, 
                 [4] => Duck 
                )

How do I create an $arrayC that takes the value from the above 2 arrays:

$arrayC = Array ( 
                 [1] => Dog, 
                 [2] => Cat, 
                 [4] => Duck 
                )

Theoretically, it's something like this:

$arrayC = Array ( 
                 [$arrayA[0]] => $arrayB[$arrayA[0]],
                 [$arrayA[1]] => $arrayB[$arrayA[1]],
                 [$arrayA[2]] => $arrayB[$arrayA[2]]
                )

Thanks.

0

5 Answers 5

7

You can do this in elegant way without foreach (Demo):

$arrayC = array_intersect_key($arrayB, array_flip($arrayA));

See array_intersect_key[Docs] and array_flip[Docs]

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

2 Comments

Very nice! Even better than mine.
+1: Would suggest this solution as well, added a demo and some links.
2
$arrayC = array();
foreach ($arrayA as $key) {
  if (isset($arrayB[$key])) {
     $arrayC[$key] = $arrayB[$key];
  }
}

Comments

1

No need to write the foreach loop yourself:

//get only the keys that are in both
$arrayA = array_intersect_key(array_fill_keys($arrayA , true), $arrayB);
$arrayB = array_intersect_key($arrayB, $arrayA);

//combine the arrays
$arrayC = array_combine(array_keys($arrayA), $arrayB);

Comments

1
foreach($arrayA as $i => $key) {
    $arrayC[$key] = $arrayB[$arrayA[$i]];
}

$arrayC will be:

Array ( [1] => Dog [2] => Cat [4] => Duck ) 

Comments

0

You can try to do something like this :-

foreach ($arrayA as $number)
{
  if(isset($arrayB[$number])
  {
    $arrayC[$number] = $arrayB[$number];
  }
}

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.