tags:

views:

136

answers:

6

I've spent hours trying to get my code to work, its a rats nest of if/elses. Basically I want to check a country name against 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 thats it.

Its sending me batty, and to be honest I'm embarassed to show you my code. Lets just say it has 2 if statements, 2 else statements and 2 foreach loops. Its a blooming mess, and I was hoping someone can dumbfound me by showing me a good way of doing this? I expect there is a way using only 1 line of code, or something sickening like that. Thank you.

+1  A: 

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

alxp
+2  A: 
$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);
}
Stefan Gehrig
+1  A: 

Why you would simpy test if the country name is contained within the string (strpos):

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

(Note the beginning and trailing ',')

It is faster than a regexp: if your ",country name," is is that string, add 'THE', else remove it.

VonC
+1  A: 

I believe you're looking for something like this:

if(in_array($country, $keywords)) {
    // add 'the'
} elseif(in_array($country, $exceptions)) {
    // remove 'the'
}
Can Berk Güder
+1  A: 

in_array() is your friend. No need to loop for it.

jishi
+3  A: 

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);
}
tvanfosson
Oops - you're right... The 'the' must be included in the array.
Stefan Gehrig
OK this is excellent.One thing though, this appears to match directly word for word. How would I go about matching cayman islands? Would I have to hard code the full string. I have a lot of 'islands' and thought one rule would do. I see the in_array() only matches on exact strings.
Pickledegg
no probs, found a custom function called substr_in_array(), sorted.
Pickledegg