Page 1 of 1
Make Switch-Case function case insensitive
Posted: Tue Feb 20, 2007 6:18 pm
by methos
1. How could I make the following code case insensitive. For example: If the switch variable $Country would be "Uk", the code would still result in "UK" ?
2. If the switch variable $Country would be "U.K.", how could I make it result in "UK" ? How could I include dots in the case ? Such as:
Code: Select all
<?php
switch ($Country){
// U.S.A.
case USA : $Country="US"; break;
case US : $Country="US"; break;
case America : $Country="US"; break;
// U.K.
case UK : $Country="GB"; break;
case Kingdom : $Country="GB"; break;
case Britain : $Country="GB"; break;
default:
$Country = "US";
}
Posted: Tue Feb 20, 2007 6:36 pm
by WaldoMonster
Here is another approach:
Code: Select all
<?php
$country = 'u.k.';
$country = strtolower($country);
if (in_array($country, array('usa', 'us', 'america'))) $country = 'US';
elseif (in_array($country, array('uk', 'u.k.', 'kingdom', 'britain'))) $country = 'GB';
else $country = 'US';
echo $country;
?>
Posted: Tue Feb 20, 2007 6:41 pm
by feyd
I think switch is better for this, but the concept transfers nicely.

Posted: Tue Feb 20, 2007 7:04 pm
by WaldoMonster
The string after case must be around single or double quotes.
Also here I have used strtolower().
Code: Select all
<?php
$Country = 'U.k.';
switch (strtolower($Country))
{
// U.S.A.
case 'usa' : $Country = 'US'; break;
case 'us' : $Country = 'US'; break;
case 'america' : $Country = 'US'; break;
// U.K.
case 'u.k.' : $Country = 'GB'; break;
case 'uk' : $Country = 'GB'; break;
case 'kingdom' : $Country = 'GB'; break;
case 'britain' : $Country = 'GB'; break;
// Default
default : $Country = 'US';
}
echo $Country;
?>
Posted: Tue Feb 20, 2007 8:57 pm
by nickvd
WaldoMonster wrote:The string after case must be around single or double quotes.
Also here I have used strtolower().
Code: Select all
<?php
$Country = 'U.k.';
switch (strtolower($Country))
{
// U.S.A.
case 'usa' : $Country = 'US'; break;
case 'us' : $Country = 'US'; break;
case 'america' : $Country = 'US'; break;
// U.K.
case 'u.k.' : $Country = 'GB'; break;
case 'uk' : $Country = 'GB'; break;
case 'kingdom' : $Country = 'GB'; break;
case 'britain' : $Country = 'GB'; break;
// Default
default : $Country = 'US';
}
echo $Country;
?>
You could take it a step futher...
Code: Select all
<?php
$Country = 'U.k.';
switch (strtolower($Country))
{
// U.K.
case 'u.k.' : case 'uk' : case 'kingdom' : case 'britain' :
$Country = 'GB';
break;
// U.S.A. / Default
case 'usa' : case 'us' : case 'america' : default :
$Country = 'US';
}
echo $Country;
?>
Posted: Wed Feb 21, 2007 2:23 am
by onion2k
You don't store your countries in a database? Odd.