Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract Array from another array using an array PHP

Tags:

arrays

php

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?

like image 821
Kevin Rave Avatar asked Dec 12 '22 01:12

Kevin Rave


2 Answers

The order of arguments is important here

 print_r(array_intersect_key($arr2, array_flip($arr1)));
like image 130
goat Avatar answered Dec 25 '22 21:12

goat


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

like image 41
Rocket Hazmat Avatar answered Dec 25 '22 19:12

Rocket Hazmat