Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

key

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); 
like image 539
maček Avatar asked Nov 23 '10 19:11

maček


People also ask

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.

What is the use of array filter in PHP?

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.

How get key from value in array in PHP?

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' ).

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.


1 Answers

With array_intersect_key and array_flip:

var_dump(array_intersect_key($my_array, array_flip($allowed)));  array(1) {   ["foo"]=>   int(1) } 
like image 106
Vincent Savard Avatar answered Nov 27 '22 02:11

Vincent Savard