PHP Array and HTML Form Drop Down List

30,395

You've forgot about $value tag. You were pasting Category name twice, instead of value. You should do that:

<select name="category_id">
<option value=""></option>
<?php 
    #                             !vCHANGEv!
    foreach($categories as $category => $value) 
    {
       $category = htmlspecialchars($category); 
       echo '<option value="'. $value .'">'. $category .'</option>';
    }
?>
</select>
Share:
30,395
Steve Kemp
Author by

Steve Kemp

Updated on July 14, 2022

Comments

  • Steve Kemp
    Steve Kemp almost 2 years

    I have a simple PHP Array called $categories that looks like this:

    Array
    (
    [Closed] => P1000
    [Open] => P1001
    [Pending] => P1002
    [In Progress] => P1003
    [Requires Approval] => P1004
    )
    

    I've got a simple HTML form that has a drop down list for one field that I would like to use the array for the options, however I only want it do show the text (e.g. Closed, Open, Pending, In Progress and Requires Approval) as the options in the drop down list but store the associated key for that option (e.g. P1000, P1001 etc) which is then sent as a POST value when the form is submitted.

    The HTML for the form field so far is:

    <select name="category_id">
    <option value=""></option>
    <?php foreach($categories as $category) {$category = htmlspecialchars($category);?>
    <option value="<?php echo $category; ?>"><?php echo $category; ?></option>
    <?php
    }
    ?>
    </select>
    

    I can get it to display either the text or the ID's but not the text and store the ID. Hopefully this is something simple that someone can point me in the right direction.

    Many thanks, Steve