Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array and select list

Tags:

php

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

The php array that I'm currently using looks like:

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

The PHP page that 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 short country code (something like 'ES', 'US', 'AN', ...) instead of numbers that I have right now as a values in this form. That short country codes I will write in this same PHP array somewhere, if it's possible.

How can I do that?

like image 684
Sergio Avatar asked Aug 24 '10 11:08

Sergio


3 Answers

Use foreach(), it's the best function to loop through 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 minor adjustements to your html code. The first option in the list will be selected by default so no need to specify it ;)

EDIT: I made some edits after reading your question again

like image 157
Christophe Avatar answered Sep 17 '22 18:09

Christophe


First make an associated array of country codes like so:

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

Then do this:

$options = '';
foreach($countries as $code => $name) {
  $options .= "<option value=\"$code\">$name</option>\n";
}
$select = "<select name=\"country\">\n$options\n</select>";
like image 26
Majid Fouladpour Avatar answered Sep 17 '22 18:09

Majid Fouladpour


Do you mean like this:

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

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

Improved version of Krike's loop, if using my array of short codes as 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>
like image 41
Jake N Avatar answered Sep 21 '22 18:09

Jake N