This article demonstrates how to filter an array in PHP. You’re given a list of permissible keys, and the solution should only retain the keys present in the list.

1. Using array_intersect_key() function

The array_intersect_key() function computes the intersection of arrays using keys for comparison. The array_intersect_key() function takes the input array to filter, and another array to compare keys against.

The following code demonstrates the usage of array_intersect_key() to filter an array. It is worth noting that the array containing the permissible keys is flipped using the array_flip() function before being passed to the array_intersect_key() function, so that its values become keys.

Download  Run Code

 
If you need to apply a more complex filter to the keys, you can do so using the array_filter() function. For example,

Download  Run Code

2. Using array_filter() function

Alternatively, you can directly invoke the array_filter() function to filter elements of an array using a callback function.

The default argument to the callback function is the array’s values. You can even specify which arguments are sent to the callback. If flag ARRAY_FILTER_USE_KEY is passed as a third parameter, the key is passed as the argument to the callback instead of the value.

Download  Run Code

 
Alternatively, you can pass ARRAY_FILTER_USE_BOTH flag to have both value and key passed as arguments to the callback function. This flag can be used to filter an array based on both keys and values, as shown below:

Download  Run Code

That’s all about filtering an array in PHP.