5

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

Edgar
  • 187
  • 1
  • 10

2 Answers2

7
<?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

Mohammed Elhag
  • 4,272
  • 1
  • 10
  • 18
  • It's not an array. They're all strings can't you see? – aldrin27 Aug 24 '15 at 00:26
  • I understand , I consider that he can get the data as array then use it – Mohammed Elhag Aug 24 '15 at 00:28
  • 1
    Just use `explode` to convert string to array. – Tim Aug 24 '15 at 00:48
  • 1
    Change your example to suit the question and add `$s = explode (',',$cities);` – Edward Aug 24 '15 at 00:50
  • Using `explode` I could get the results I needed, thanks – Edgar Aug 24 '15 at 00:54
  • of course you are right if he want to change it from string to array and that means he has output as string. this question maybe vague and what i understand is that he try to get some data in strings like what he mentioned , then check if a certain value is exist,and i suggest to get data as array because it is more easy then search by in array method – Mohammed Elhag Aug 24 '15 at 00:55
3

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";
}
crafter
  • 6,246
  • 1
  • 34
  • 46