Wednesday, 3 January 2018

PHP Get State Abbreviations from Name or Abbreviations from State Names

<?php
function state_abbr($name, $get = 'abbr') {
//make sure the state name has correct capitalization:
    if($get != 'name') {
    $name = strtolower($name);
    $name = ucwords($name);
    }else{
    $name = strtoupper($name);
    }
$states = array(
'Alabama'=>'AL',
'Alaska'=>'AK',
'Arizona'=>'AZ',
'Arkansas'=>'AR',
'California'=>'CA',
'Colorado'=>'CO',
'Connecticut'=>'CT',
'Delaware'=>'DE',
'Florida'=>'FL',
'Georgia'=>'GA',
'Hawaii'=>'HI',
'Idaho'=>'ID',
'Illinois'=>'IL',
'Indiana'=>'IN',
'Iowa'=>'IA',
'Kansas'=>'KS',
'Kentucky'=>'KY',
'Louisiana'=>'LA',
'Maine'=>'ME',
'Maryland'=>'MD',
'Massachusetts'=>'MA',
'Michigan'=>'MI',
'Minnesota'=>'MN',
'Mississippi'=>'MS',
'Missouri'=>'MO',
'Montana'=>'MT',
'Nebraska'=>'NE',
'Nevada'=>'NV',
'New Hampshire'=>'NH',
'New Jersey'=>'NJ',
'New Mexico'=>'NM',
'New York'=>'NY',
'North Carolina'=>'NC',
'North Dakota'=>'ND',
'Ohio'=>'OH',
'Oklahoma'=>'OK',
'Oregon'=>'OR',
'Pennsylvania'=>'PA',
'Rhode Island'=>'RI',
'South Carolina'=>'SC',
'South Dakota'=>'SD',
'Tennessee'=>'TN',
'Texas'=>'TX',
'Utah'=>'UT',
'Vermont'=>'VT',
'Virginia'=>'VA',
'Washington'=>'WA',
'West Virginia'=>'WV',
'Wisconsin'=>'WI',
'Wyoming'=>'WY'
);
    if($get == 'name') {
    // in this case $name is actually the abbreviation of the state name and you want the full name
    $states = array_flip($states);
    }
return $states[$name];
}
//test function:
$state = "OHIO";
$state_a = state_abbr($state);
echo "<p>The abbreviation for $state is $state_a</p>";
$state = "ohio";
$state_a = state_abbr($state);
echo "<p>The abbreviation for $state is $state_a</p>";
$state = "Ohio";
$state_a = state_abbr($state);
echo "<p>The abbreviation for $state is $state_a</p>";
$state = "oHIo";
$state_a = state_abbr($state);
echo "<p>The abbreviation for $state is $state_a</p><hr />";
$state = "oh";
$state_a = state_abbr($state, "name");
echo "<p>The abbreviation $state is for $state_a</p>";
$state = "Oh";
$state_a = state_abbr($state, "name");
echo "<p>The abbreviation $state is for $state_a</p>";
$state = "OH";
$state_a = state_abbr($state, "name");
echo "<p>The abbreviation $state is for $state_a</p>";
?>

0 comments:

Post a Comment