How to filter an array by its keys using an array of allowed keys with PHP?

Spread the love

Sometimes, we want to filter an array by its keys using an array of allowed keys with PHP.

In this article, we’ll look at how to filter an array by its keys using an array of allowed keys with PHP.

How to filter an array by its keys using an array of allowed keys with PHP?

To filter an array by its keys using an array of allowed keys with PHP, we can use the array_intersect_key function.

For instance, we write

$allowed = ["foo", "bar"];

var_dump(array_intersect_key($my_array, array_flip($allowed)));

to call array_intersect_key with $my_array and the values we get from the $allowed array to return an new array that has the keys that are in the $allowed array.

Conclusion

To filter an array by its keys using an array of allowed keys with PHP, we can use the array_intersect_key function.

Leave a Reply

Your email address will not be published.