eHow launches Android app: Get the best of eHow on the go.

How To

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

Member
By Yojance
User-Submitted Article
(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.

Difficulty: Moderately Easy
Instructions

Things You'll Need:

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

    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.

  2. Step 2
    Image depicting the function and array already in our code.
     
    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.

  3. Step 3
    Foreach loop in action.
     
    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.

  4. Step 4
    Image depicting how the function looks at the end.
     
    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  

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!

Subscribe

Post a Comment

Post a Comment

Related Ads

  • Have you done this? Click here to let us know.
I Did This
Get Free Internet Newsletters

Copyright © 1999-2009 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy .   en-US Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License. † requires javascript

Demand Media
eHow_eHow Technology and Electronics