PHP array and select list

I want to use a php array to select an HTML list. In this case, it will be a list of countries, but in addition to the name of the country, which is listed in the drop-down list, I need as the value of a short country code for each country.

The php array that I am currently using looks like this:

$wcr=array( 'Angola', 'Antigua & Barbuda', 'Armenia', 'Austria', 'Azerbaijan', ..... ); 

PHP page using this array:

 <select name="country"><option selected value=""> --------- <? $p=1;asort($wcr);reset($wcr); while (list ($p, $val) = each ($wcr)) { echo '<option value="'.$p.'">'.$val; } ?> </select> 

The value should be a short country code (something like "ES", "US", "AN", ...) instead of the numbers that I now have as the values ​​in this form. In these short country codes, I will write in the same PHP array somewhere, if possible.

How can i do this?

+4
source share
4 answers

Use foreach (), this is the best function to loop around arrays

your array should look like jakenoble posted

 <select name="country"> <option value="">-----------------</option> <?php foreach($wcr as $key => $value): echo '<option value="'.$key.'">'.$value.'</option>'; //close your tags!! endforeach; ?> </select> 

I also made some small adjustments for your html code. The first option in the list will be selected by default, so it does not need to be specified;)

EDIT: I made some changes after reading your question again

+21
source

You mean the following:

  $wcr=array( "ANG" = > 'Angola', "ANB" = > 'Antigua & Barbuda', "ARM" = > 'Armenia', "AUS" = > 'Austria', "AZB" = > 'Azerbaijan' ); 

Then, in your while loop, $p is your short code.

An improved version of the Krike loop if using an array of short codes in the form of array keys:

 <select name="country"> <option value="">-----------------</option> <?php asort($wcr); reset($wcr); foreach($wcr as $p => $w): echo '<option value="'.$p.'">'.$w.'</option>'; //close your tags!! endforeach; ?> </select> 
+3
source

First, create a linked array of these country codes:

 $countries = array( 'gb' => 'Great Britain', 'us' => 'United States', ...); 

Then do the following:

 $options = ''; foreach($countries as $code => $name) { $options .= "<option value=\"$code\">$name</option>\n"; } $select = "<select name=\"country\">\n$options\n</select>"; 
+3
source

If you use an array like jakenoble shows, I would use foreach ().

 $wcr=array( "ANG" = > 'Angola', "ANB" = > 'Antigua & Barbuda', "ARM" = > 'Armenia', "AUS" = > 'Austria', "AZB" = > 'Azerbaijan' ); 

So, Foreach will look something like this:

 foreach($wcr as $short_code => $descriptive) { ?> <option value="<?php echo $short_code; ?>"><?php echo $descriptive; ?></option> <?php } 
+1
source

All Articles