The callback function in array_filter()
only passes in the array's values, not the keys.
If I have:
$my_array = array("foo" => 1, "hello" => "world"); $allowed = array("foo", "bar");
What's the best way to delete all keys in $my_array
that are not in the $allowed
array?
Desired output:
$my_array = array("foo" => 1);
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.
Definition and Usage The array_filter() function filters the values of an array using a callback function. This function passes each value of the input array to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.
If you have a value and want to find the key, use array_search() like this: $arr = array ('first' => 'a', 'second' => 'b', ); $key = array_search ('a', $arr); $key will now contain the key for value 'a' (that is, 'first' ).
The array_keys() function returns an array containing the keys.
With array_intersect_key
and array_flip
:
var_dump(array_intersect_key($my_array, array_flip($allowed))); array(1) { ["foo"]=> int(1) }
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