Skip to content

How to filter a PHP array by key?

PHP array_intersect_key() function returns an array containing all the entries of primary array which have keys that are preset in all the arguments. This function computes the intersection of arrays using keys for comparison. Here we will provide a short PHP code snippets to filter elements of an array that contain a specific key. It will help you to filter an array based on particular key.

The following example code will filter the elements of an array by key using array_intersect_key() and array_flip() functions in PHP.

function getGivenKeyValuesFromArray($inputArray,$keyArray) {
  return array_intersect_key($inputArray, array_flip($keyArray));
}

$input = array("oranges", "apples", "pears");
print_r(getGivenKeyValuesFromArray($input,[1]));

As I mentioned above array_intersect_key computes the intersection of arrays using keys, so in order to take advantage of this behavior we are converting second array values into keys and keys into values using array_flip.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments