$array1 = ['key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3']
$array2 = ['key1','key3']
I want to get all elements from array1 that has keys in array2. So the result should be:
$result = ['key1'=>'val1', 'key3'=>'val3']
I tried array_intersect_key($array1, $array2) but that doesn't work. What is the fastest way to get the above result?
Edit: Forgot to mention that array2 maybe a associative array or single dimension.
You need to make key1 and key2 the keys in the second array before you can use array_intersect_key(): use array_flip() to do that
$result = array_intersect_key($array1,array_flip($array2));
EDIT
It doesn't matter if $array2 is associative or not:
$array1 = array('key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3');
$array2 = array('first'=>'key1','second'=>'key3');
$filteredData = array_intersect_key($array1,array_flip($array2));
var_dump($filteredData);
still gives
array
'key1' => string 'val1' (length=4)
'key3' => string 'val3' (length=4)
Not a purely elegant one-liner, but it'll work:
$result = array();
foreach($array2 as $key) {
$result[$key] = $array1[$key];
}
In response to edit, just use values($array2)
.
function my_intersect($a1, $a2){
$func = function(&$v, $k) {
$v = (is_string($k)) ? $k : $v;
};
array_walk($a2, $func);
$a2 = array_fill_keys(array_values($a2),1);
$ret = array();
if ($a1){
foreach($a1 as $k => $v){
if (array_key_exists($k, $a2)){
$ret[$k] = $v;
}
}
}
return $ret;
}
Kind of ugly by I think it's what the asker wants? Likely a better way.