Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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');
like image 938
Lhuqita Fazry Avatar asked Aug 18 '11 13:08

Lhuqita Fazry


People also ask

How do you filter an associative array?

Example-3: Filter an associative array using an objectThe array_filter() function will filter those elements where the values are 'Present'. echo "Present applicants = ".

How do you find the associative array of a key?

Answer: Use the PHP array_keys() function You can use the PHP array_keys() function to get all the keys out of an associative array.

How do you filter an array key?

Filtering a PHP array by keys To use the PHP array_filter() function to filter array elements by key instead of value, you can pass the ARRAY_FILTER_USE_KEY flag as the third argument to the function. This would pass the key as the only argument to the provided callback function.


2 Answers

$keys = array_flip($B);
$C = array_intersect_key($A,$keys);
like image 185
Jon Page Avatar answered Oct 27 '22 00:10

Jon Page


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?

like image 38
Simon Elliston Ball Avatar answered Oct 26 '22 22:10

Simon Elliston Ball