How to filter an associative arrays using array of keys in PHP?

Lhuqita Fazry picture Lhuqita Fazry · Aug 18, 2011 · Viewed 7.3k times · Source

I have an associative arrays and an array of keys.

$A = array('a'=>'book', 'b'=>'pencil', 'c'=>'pen');
$B = array('a', 'b');

How I build an associative array from all element of $A where the key is in $B? For the example above, the answer should be

$C = array('a'=>'book', 'b'=>'pencil');

Answer

Jon Page picture Jon Page · Aug 18, 2011
$keys = array_flip($B);
$C = array_intersect_key($A,$keys);