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

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


$keys = array_flip($B);$C = array_intersect_key($A,$keys);


array_intersect_key($A,array_combine($B,$B))

or better: array_intersect_key($my_array, array_flip($allowed))

from the question: PHP: How to use array_filter() to filter array keys?


Here's a simple solution which checks that the key exists in $A before appending it to $C

$A = array('a'=>'book', 'b'=>'pencil', 'c'=>'pen');$B = array('a', 'b');$C = array();foreach ($B as $bval) {  // If the $B key exists in $A, add it to $C  if (isset($A[$bval])) $C[$bval] = $A[$bval];}var_dump($C);// Prints:array(2) {  ["a"]=>  string(4) "book"  ["b"]=>  string(6) "pencil"}