Sometimes there is a need to find a key/s of an array that matches a particular pattern. array_search searches the array for a given value and returns the corresponding key but it matches the entire word.

Here’s a scenario. You have a list of tags and you want to provide a user to seach a particular tag which closely matches to their search.

So here are some of the tags in an array

If the user enters WordPress we want to show WordPress Plugins as well as WordPress Tweaks. So this is how it can be done using preg_grep

where $key is the user input i.e. WordPress in this case

In our case $filtered_tags will be an array and will return

0=>Wordpress Plugins

1=>Wordpress Tweaks


Leave a Reply

Your email address will not be published. Required fields are marked *