Add / remove the word "The" in certain countries

I spent hours trying to get my code to work, its a rat's nest if / elses. Basically I want to check the country name for these two arrays:

//if its in this array add a 'THE'    
$keywords = array("bahamas","island","kingdom","republic","maldives","netherlands",
                  "isle of man","ivory","philippines","seychelles","usa");
    //if its in this array, take THE off!
    $exceptions = array("eire","hispaniola");

      

and this.

Batty sends me and to be honest I am embarrassed to show you my code. Let's just say it has 2 if statements, 2 else statements, and 2 foreach loops. Its a blooming mess and I was hoping someone could numb me by showing me a good way to do it? I expect there is a way to use just one line of code or something like that. Thank.

0


source to share


6 answers


This builds on @ sgehrig's answer, but note the change in your exceptions:



//if its in this array add a 'THE'    
$keywords = array("bahamas","island","kingdom","republic","maldives","netherlands",
                  "isle of man","ivory","philippines","seychelles","usa");
//if its in this array, take THE off!
$exceptions = array("the eire","the hispaniola");

$countryKey = strtolower($country);
if (in_array($countryKey, $keywords)) {
    $country = 'The ' . $country;
} else if (in_array($countryKey, $exceptions)) {
    $country = substr($country, 4);
}

      

+3


source


$countryKey = strtolower($country);
if (in_array($countryKey, $keywords)) {
    $country = 'The' . $country;
} else if (in_array($countryKey, $exceptions) && stripos($country, 'the ') === 0) {
    $country = substr($country, 4);
}

      



+2


source


The easiest way would be to split it into two steps, declare "the" for the countries that match the first list, and then just delete it if it matches the words in the second list.

+1


source


Why would you check if the country name is in the line ( strpos ):

",bahamas,island,kingdom,republic,maldives,netherlands,isle of man,ivory,philippines,seychelles,usa,"

      

(Note the beginning and end ",")

This is faster than a regular expression: if your "country name" is this line, add "THE" and then remove it.

+1


source


I believe you are looking for something like this:

if(in_array($country, $keywords)) {
    // add 'the'
} elseif(in_array($country, $exceptions)) {
    // remove 'the'
}

      

+1


source


in_array () is your friend. Don't dwell on it.

+1


source







All Articles