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');
Example-3: Filter an associative array using an objectThe array_filter() function will filter those elements where the values are 'Present'. echo "Present applicants = ".
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.
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.
$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?
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