0

I have a $user_location variable which contains a current user city, and need to compare that variable with a database query to check if $user_location is LIKE the $item_coverage ($item_coverage is the result of the query).

$item_coverage contains a list of cities separated by a comma "," and $user_location too.

Just need to walk through all words separated by comma and contained in $item_coverage and check if one of those words match $user_location, if one-word match {give some result} else if don't {give another result}

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345

1 Answers1

-2

If $user_location is only one city, you can use explode() and in_array() like this

$cities = explode(',', $item_coverage);

if (in_array($user_location, $cities)) {
    // The user's city is contained in $item_coverage
} else {
    // Not contained in $item_coverage
}

If $user_location is an array containing several cities, you can use explode(), array_intersect() and empty() like this

$cities = explode(',', $item_coverage);
$to_check = explode(',', $user_location);

if (!empty(array_intersect($to_check, $cities))) {
    // At least one of the user's cities are contained in $item_coverage
} else {
    // None is contained in $item_coverage
}
  • Now testing, I'll share you the results. – Guillermo Esquivel Apr 03 '17 at 20:29
  • My bad, you would use LIKE and not = ! Maybe be trying to make the `$user_location` and `$cities` value with lowercase or something like that? Have you an exemple of the cities set in your database and what the user might fill in the city's input? – Florent Banneux Apr 03 '17 at 20:34
  • Missing a comma in ```$cities = explode(',', $item_coverage);``` – Oluwafemi Sule Apr 03 '17 at 20:39
  • Thanks for your answer, in $item_coverage I have: Mexico City, Monterrey, Cancun – Guillermo Esquivel Apr 03 '17 at 20:41
  • My bad @OluwafemiSule.. I just think about that but, if all the cities are written in the same column and seperate by "," you can use LIKE "%$city%" in your SQL! Like: `('SELECT [fields] FROM [table] WHERE [column_cities] LIKE "%$user_location%"')`, if you have a result, it means that the city exist in your database (hope i'm right) – Florent Banneux Apr 03 '17 at 20:48