PHP Function for a List of States for HTML Forms
The following php function produces the following textbox:
It is useful for keeping your main code clean and legible--just stick this function in an external file and call it whenever necessary. It records the states as two-letter abbreviations and displays them in full. It can be easily edited to include any additional territories or converted to use for countries.
function displaystatebox() {
$states = array(
array("AL", "Alabama"),
array("AK", "Alaska"),
array("AZ","Arizona"),
array("AR","Arkansas"),
array("CA","California"),
array("CO","Colorado"),
array("CT","Connecticut"),
array("DE","Delaware"),
array("DC","Dist of Columbia"),
array("FL","Florida"),
array("GA","Georgia"),
array("HI","Hawaii"),
array("ID","Idaho"),
array("IL","Illinois"),
array("IN","Indiana"),
array("IA","Iowa"),
array("KS","Kansas"),
array("KY","Kentucky"),
array("LA","Louisiana"),
array("ME","Maine"),
array("MD","Maryland"),
array("MA","Massachusetts"),
array("MI","Michigan"),
array("MN","Minnesota"),
array("MS","Mississippi"),
array("MO","Missouri"),
array("MT","Montana"),
array("NE","Nebraska"),
array("NV","Nevada"),
array("NH","New Hampshire"),
array("NJ","New Jersey"),
array("NM","New Mexico"),
array("NY","New York"),
array("NC","North Carolina"),
array("ND","North Dakota"),
array("OH","Ohio"),
array("OK","Oklahoma"),
array("OR","Oregon"),
array("PA","Pennsylvania"),
array("RI","Rhode Island"),
array("SC","South Carolina"),
array("SD","South Dakota"),
array("TN","Tennessee"),
array("TX","Texas"),
array("UT","Utah"),
array("VT","Vermont"),
array("VA","Virginia"),
array("WA","Washington"),
array("WV","West Virginia"),
array("WI","Wisconsin"),
array("WY","Wyoming")
);
print '<select name="state">' . "\n";
foreach ($states as $s) {
print '<option value="' . $s[0] . '">' . $s[1] . "</option>\n";
}
print "</select>\n";
}
Other Useful Form Functions
I find these functions useful when creating large forms:
Textbox
Use this function to display textboxes. There are several different variations possible, depending on how much control you need over the final textbox.
print '<input type="text" name="' . $name . '">';
}
The code produced by the above with "mytextbox" passed as the variable looks like this:
<input type="text" name="mytextbox">
The textbox itself looks like this:
You can modify this function by adding additional variables to control width, value, background, etc.
Radio Buttons
If you have a ton of radio buttons to display, this is a great time-saver. This is especially useful when combined with a for or while loop that cycles through an array of options.
print '<input type="radio" name="' . $name . '">' . $display . "<br>\n";
}
The code produced by the above with "xxx" passed as $name and "Option 1" passed as $display looks like this:
<input type="radio" name="xxx"> Option 1<br>
The output itself looks like this: Option 1
