Tuesday, November 3, 2015

Filter values from an array similar to SQL LIKE '%search%' using PHP

Array search or array filter similar to SQL LIKE '%search%' in PHP.

In one of my project, I need to display all the country names in select option as a drop down list.

Client expected filter option based on user input.
Ex: If user type "IN", we need to display country name starts with "IN".

Result like "INDIA", "INDONESIA", etc ..

Used below code to achieve it.
 $input = preg_quote('IN', '~');
 $result = preg_grep('~^' . $input . '~i', $list); // List is PHP array of values
// ~^ - to start from beginning.
// ~i - for case insensitive
Original post https://stackoverflow.com/questions/5808923/filter-values-from-an-array-similar-to-sql-like-search-using-php/5809221#5809221

No comments:

Post a Comment