1

I have an array:

array(
  '1' => red,
  '2' => green,
  '3' => blue,
  '4' => orange
);

And a second array:

array(
  '0' => 1,
  '1' => 4
);

I want to keep only those elements in Array 1 that have a key value equal to a value in Array 2.

So the final array should look like:

array (
    '1' => red,
    '4' => orange
);
1
  • 2
    What have you tried? We are happy to help you fix problems in your existing code, but we will not (in most cases) write the code for you. Commented Mar 5, 2012 at 21:46

2 Answers 2

3

Use array_intersect_key to get the values that share keys (after using array_flip on the 2nd array).

$array3 = array_intersect_key($array1, array_flip($array2));
Sign up to request clarification or add additional context in comments.

2 Comments

This will not preserve the values from $array1. The result is Array ( [1] => 0 [4] => 1 ).
@GeorgeCummins: I fixed it. I had the parameters reversed. It works correctly now :-)
1

Use array_intersect_key with array_flip,

$r = array_intersect_key($a, array_flip($b));

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.