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?
The order of arguments is important here
print_r(array_intersect_key($arr2, array_flip($arr1)));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With