4

I have two arrays like this

 $arr1 = Array('fn', 'ln', 'em');
 $arr2 = Array('fn'=>'xyz',  'ano' => 'abc', 'ln'=>'122', 'em' => '[email protected]', 'db'=>'xy');

I want to create an array from arr2 with all the elements from $arr1. So the result should be like this.

 $result = Array( 'fn'=>'xyz', 'ln'=>'122', 'em'='[email protected]');

Don't want to loop.

Any idea?

2
  • "Don't want to loop." Why not? Commented Jun 8, 2012 at 20:31
  • 1
    @Rocket. I think there should be function that should be able to do this. Its a simple task. Commented Jun 8, 2012 at 20:33

3 Answers 3

9

The order of arguments is important here

 print_r(array_intersect_key($arr2, array_flip($arr1)));
Sign up to request clarification or add additional context in comments.

1 Comment

@KevinRave: A up-vote is +10, you can also give it a +15 by marking it "accepted" (the checkmark under the votes) :-P
4

You can use array_map for this.

// PHP 5.3+ only
$result = array_combine($arr1, array_map(function($a) use($arr2){
    return $arr2[$a];
}, $arr1));

DEMO: http://codepad.viper-7.com/Y1aYcf

If you have PHP < 5.3, you can do some trickery with array_intersect_key and array_flip.

$result = array_intersect_key($arr2, array_flip($arr1));

DEMO: http://codepad.org/MuydURQT

Comments

0

You just have to loop, as in create a new array or maybe check some array set in mathematics functions. I think, maybe, insection might work.

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.