Jump to content

need help with select menu in php


doforumda

Recommended Posts

hi

i want to create a select menu where all the countries will reside. By making it through pure xhtml there will be lots of option tags. So what i want is make a php function so it generates all these countries name and by calling it in option tag it automatically fill the select menu with all these countries.

 

Is this possible if yes then please help me how it can be done? I want to use functions not classes.

Link to comment
https://forums.phpfreaks.com/topic/196079-need-help-with-select-menu-in-php/
Share on other sites

you need something that will store all the country data for you. i would suggest either:

1. an array that is declared in the php file itself (perhaps inside the function itself) OR

2. a text file that can be read and parsed into an array.

 

I will use no. 1 for simplicity sake in the example.

 

You want to create something like:

<select name="country">

<option value="au">Australia</option>

<option value="us">United States</option>

<option value="jp">Japan</option>

etc.

</select>

 

dont you? but have all the <option> tags made by the function?

 

function createCountryOptions($countries)
{
   if (is_array($countries))
   {
      $returnString = '';
      foreach ($countries as $countryCode => $countryName) // loop through country data
      {
         $returnString .= '<option value="'.$countryCode.'">'.$countryName.'</option>'; // build option values into a string
      }
      $returnString .= "\n"; // tack a newline char on the end of the options
      return($returnString);
   }
   else
   {
      print('function::createCountryFunctions() failed - parameter passed to function is not an array as expected.<br/>'."\n"); // output error - parameter is not an array
      return(FALSE); // return FALSE
   }
}

// main script
$countryArray = array('au' => 'Australia', 'us' => 'United States', 'jp' => 'Japan'); // etc for all your countries in list
$output = '<html><head><title>Countries</title></head><body>'."\n";
$output .= '<form action="handlingScript.php" method="POST">'."\n";
$output .= '<select name="country">';
$output .= createCountryOptions($countryArray);
$output .= '</select>'."\n";
print($output);

 

ps: there are probably heaps of these functions all over the internet if you google for it. save you the trouble of typing out country names.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.