PHP array and select list

后端 未结 4 1135
一整个雨季
一整个雨季 2020-12-16 20:47

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

相关标签:
4条回答
  • 2020-12-16 20:51

    If you are using this sort of array as shown by jakenoble I would use foreach().

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

    So the Foreach would look something like:

    foreach($wcr as $short_code => $descriptive) {
        ?>
        <option value="<?php echo $short_code; ?>"><?php echo $descriptive; ?></option>
        <?php
    }
    
    0 讨论(0)
  • 2020-12-16 21:07

    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

    0 讨论(0)
  • 2020-12-16 21:08

    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>
    
    0 讨论(0)
  • 2020-12-16 21:16

    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>";
    
    0 讨论(0)
提交回复
热议问题