I like to reuse code as much as possible and if there’s underyling data in something I’ll use again, I’ll put that data in some extractable form in an EAV (Entity, Attribute, Value) database table so I don’t need to maintain the data anywhere except one place.
So in the example below where the variable $jsonText is being assigned, I actually have a method called getFormChoices(‘states’) that pulls this $jsonText automatically, from anywhere. In Symfony, the getFormChoices() is a method I use in a base repository class that all other repositories extend and therefore inherit automatically. This is efficient since certain higher-level global functions are all accessible and maintained in a single “Base Repository” class.
<?php
$jsonText='{"AL" : "Alabama", "AK" : "Alaska", "AZ" : "Arizona", "AR" : "Arkansas", "CA" : "California", "CO" : "Colorado", "CT" : "Connecticut", "DE" : "Delaware", "FL" : "Florida", "GA" : "Georgia", "HI" : "Hawaii", "ID" : "Idaho", "IL" : "Illinois", "IN" : "Indiana", "IA" : "Iowa", "KS" : "Kansas", "KY" : "Kentucky", "LA" : "Louisiana", "ME" : "Maine", "MD" : "Maryland", "MA" : "Massachusetts", "MI" : "Michigan", "MN" : "Minnesota", "MS" : "Mississippi", "MO" : "Missouri", "MT" : "Montana", "NE" : "Nebraska", "NV" : "Nevada", "NH" : "New Hampshire", "NJ" : "New Jersey", "NM" : "New Mexico", "NY" : "New York", "NC" : "North Carolina", "ND" : "North Dakota", "OH" : "Ohio", "OK" : "Oklahoma", "OR" : "Oregon", "PA" : "Pennsylvania", "RI" : "Rhode Island", "SC" : "South Carolina", "SD" : "South Dakota", "TN" : "Tennessee", "TX" : "Texas", "UT" : "Utah", "VT" : "Vermont", "VA" : "Virginia", "WA" : "Washington", "WV" : "West Virginia", "WI" : "Wisconsin", "WY" : "Wyoming"}';
$jsonArr=json_decode($jsonText,true);
echo $jsonArr['VT']."<br/>"; // will return "Vermont"
// Build an HTML form SELECT pulldown with state acronyms as keys and the state names spelled out as display values:
$out="<select name='states'>";
foreach($jsonArr as $key=>$val){
$out.="<option value='$key'>$val</option>";
}
$out.="</select>";
echo "Select your state: $out";
Please feel free to use parts or all of this script below in your own PHP projects. Some old school developers might remember 1999 hard-coding every state as an HTML SELECT option — yet, there are still web developers out there that spend time remaking these over and over. Your company pays for this inefficiency in a big way — projects don’t get completed as fast as they could or should, for one. Do you suspect your web department is complacent and inefficient? Ask them what they are doing to be efficient and reduce code maintenance later. If your web developers don’t have a clear answer, chances are they haven’t adapted in 5 years and your systems and code will reflect this apathy.
Like this:
Like Loading...