Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Check if word is inside a group of words [duplicate]

Tags:

php

I have a group of cities and I want to see if a certain string contains a city from one in the group, if it does it will echo Yes. I was thinking to write all cities in a string, separated by commas.

$cities = "'Zimbabue', 'France', 'Sao Paulo'";

How can this be achieved ? if not separated by commas, with something else.

Edit=

strpos cant be used, if the string contaning all cities contains "São Paulo" and I try to find Paulo, it will output true but should be false

like image 997
Edgar Avatar asked Aug 24 '15 00:08

Edgar


2 Answers

<?php
 $os = array("Mac", "NT", "Irix", "Linux");
 if (in_array("Irix", $os)) {
echo "Got Irix";
  }
  if (in_array("mac", $os)) {
   echo "Got mac";
  }
  ?>

http://php.net/manual/en/function.in-array.php

like image 123
Mohammed Elhag Avatar answered Sep 22 '22 03:09

Mohammed Elhag


You can combine the in_array and explode functions

echo ((in_array($searchTerm, explode(",", $cities)))?"Yes":"No");

or if you want a more readable version

$resultArray = explode(",", $cities);
$result = (in_array($searchTerm, $resultArray);
if ($result) {
   echo "Yes"
} else {
   echo "No";
}
like image 34
crafter Avatar answered Sep 22 '22 03:09

crafter