I have a MySql table that stores the users state and city from a list of states and cities. I specifically coded each state as their two letter shortened version (like WA for Washington and CA for California) and every city has the two letter abbreviation and the city name formated like this: Boulder Colorado would be CO-boulder
and Salt Lake City, Utah would be UT-salt-lake-city
as to avoid different states with same city name. The PHP inserts the value (UT-salt-lake-city
) under the column City
, but when I call the variable through PHP, it displays like this: Your location is: UT-salt-lake-city, Utah.
To solve this, I've been making this list of variables
if ($city == "AL-auburn") { $city = "Auburn"; }
else if ($city == "AL-birmingham") { $city = "Birmingham"; }
else if ($city == "GA-columbus") { $city = "Columbus"; $state = "Georgia"; }
else if ($city == "AL-dothan") { $city = "Dothan"; }
else if ($city == "AL-florence") { $city = "Forence"; }
else if ($city == "AL-muscle-shoals") { $city = "Muscle Shoals"; }
else if ($city == "AL-gadsden-anniston") { $city = "Gadsden Anniston"; }
else if ($city == "AL-huntsville") { $city = "Huntsville"; }
else if ($city == "AL-decatur") { $city = "Decatur"; }
else if ($city == "AL-mobile") { $city = "Mobile"; }
else if ($city == "AL-montgomery") { $city = "Montgomery"; }
else if ($city == "AL-tuscaloosa") { $city = "Tuscaloosa"; }
Is there a way I can shorten this process or at least call it from a separate file so I don't have to copy/paste every time I want to call the location?
What about something like
$name = 'UL-salt-lake-city';
ucwords(str_replace("-"," ",substr($name, 3)));
Converts to "Salt Lake City"
If you need to have names which do not directly correspond to their codes, you can use an associative array:
$city_names = array(
'CO-boulder' => 'Boulder, Colorado',
'GA-columbus' => 'Columbus, Georgia',
// ...
);
$name = $city_names[$city];
You need a hashmap here, you can do that as an array in PHP:
$cities = array(
"AL-auburn" => array("Auburn"),
"AL-birmingham" => array("Birmingham"),
"GA-columbus" => array("Columbus", "Georgia"),
...
);
if (isset($cities[$city])) {
list($city, $state) = $cities[$city] + array(null, null);
}
You can also store the cities array then.
Alternatively you can make use of the existing information:
list($state, $city) = explode('-', $city, 2);
$city = ucwords(strtr($city, '-', ' '));
You can then map the state 2-letter-codes with a hashmap to their long names again:
$states = array(
'AL' => 'Alabama',
'GA' => 'Georgia',
...
);
if (isset($states[$state])) {
$state = $states[$state];
}