How to Populate a Drop Down List With All 50 States Using PHP

By Yojance

Rate: (3 Ratings)

Learn how to easily write a PHP function which will be able to generate all the HTML code of a Drop Down List containing all 50 states.

Instructions

Difficulty: Moderately Easy

Things You’ll Need:

  • Notepad
  • Hosting account with PHP
  • FTP (if no file manager is provided)

Step1
The first thing we need to do is create a new document, I'll be using DreamWeaver CS3, but you can use your favorite text editor; Notepad will be fine.
Now we need to write some code. We are going to create our function GetStats() and put all the code inside it.
Step2
Image depicting the function and array already in our code. The states are going to be inside an array, this will help us loop through each, one at a time using a foreach loop.
Step3
Foreach loop in action. Next all we need to do is cycle through each state in the array using a foreach loop and create the necessary HTML code for it. Note that we only want to repeat the options code, which is why that's the only HTML inside our loop.
The select portion of the HTML code is left outside the loop, otherwise it would create a Drop Down List for every state and we don't want that to happen here.
Step4
Image depicting how the function looks at the end. This is how the function should look like in your code in order to work correctly. Don't forget to call the function where you want the drop down list to appear like this: GetStates();

Tips & Warnings

  • Review the code and test it on your server before using it on the real world.
  • Those \t and \n are there so the HTML code is better to read once generated.
  • If you are using Notepad, make sure you save your file with double quotes at the beginning and end, like this: "filename.php" .Otherwise, the file will be named filename.php.txt with two file extensions and it won't work.

Comments

| View All Comments

mbsan4 said

Flag This Comment

on 11/14/2007 This a great article, very helpuful! thank you!

mbsan4 said

Flag This Comment

on 11/14/2007 This a great article, very helpuful! thank you!

View All

Post a Comment

POST A COMMENT

Request a New How-To Article

Looking for more How To information? Chances are there’s an eHow member who knows how to do what you’re looking to do. Submit an article request now!

eHow Article:  How to Populate a Drop Down List With All 50 States Using PHP

eHow Member: Yojance

Yojance

Novice Novice | 130 Points

Category: Internet

Articles: See my other articles

Related Ads

Internet

Veesites
Meet Virginia DeBolt eHow’s Internet Expert.