jump to navigation

Country List Generator for a PHP-form November 5, 2011

Posted by Tournas Dimitrios in PHP.
trackback

The following PHP snippet will generate a drop-down or an unordered list of countries to use in a form or display in your web page . This is great for use in a registration or contact form on your web site .  A function ” countrylist() ” has three optional parameters :

  • action :  “dropdown”  or “list” ( default is dropdown) .
  • style  :  “fullname” or “code” ( default is fullname ) .
  • selectedid : default is “null”  , set a pre-selected country-name

Using the code is simple , just import the function and call the function (as default or with options ) into the form where a country drop-down needs to be displayed .

<?php include('countrylist.php'); ?>
<?php countrylist() ; ?>
// OR 
<?php countrylist('dropdown',' code ','Zimbabwe'); ?>

The code of the function is :

<?php

function countrylist($action = 'dropdown', $style = 'fullname' , $selectedid = 'null') {
$countryName_list = array(
"Afghanistan", "Albania", "Algeria", "Andorra",
"Zambia", "Zimbabwe"
);
$countryCode_list = array(
'AD' => 'Andorra',
'ZM' => 'Zambia',
'ZW' => 'Zimbabwe'
);

if (($action == 'dropdown')&& ($style == 'fullname')) {
echo '<select name="country">';
foreach ($countryName_list as $country) {
echo "<option value=\"".$country."\"";
if (!empty($selectedid)) {
if ($selectedid == $country) {
echo " selected=\"selected\"";
}
}
echo ">".$country."</option>\n";
}
echo '</select> ';

}
elseif(($action == 'dropdown')&& ($style == 'code')) {
echo '<select name="country">';
foreach($countryCode_list as $countryCode => $country) {
echo "<option value=\"".$country."\"";
if (!empty($selectedid)) {
if ($selectedid == $country) {
echo " selected=\"selected\"";
}
}
echo ">".$countryCode."</option>\n";
}
echo '</select> ';

}
elseif ($action == 'list') {
echo '<ul name="country">';
foreach ($countryName_list as $country) {
echo "<li>".$country."</li>\n";
}
echo '</ul> ';
}
}
?>

The list of countries  is truncated in the above code , download the complete function .

Advertisements

Comments»

1. Permalink - March 11, 2013

Outstanding post however I was wanting to know if you could write a
litle more on this subject? I’d be very grateful if you could elaborate a little bit further. Appreciate it!

tournasdimitrios1 - March 11, 2013

@Permalink
I would be glad to help out , if you have a specific question on the subject of this article .


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s