3

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

5 Answers 5

5

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Robik and everyone else who pointed out the same thing - was not getting the key for each value in the array. Everything is working great now. Many thanks to all.
0

As you have to include key and value both key is to show the text and value for POST

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

Comments

0

you have not included keys in foreach loop

foreach($categories as $id=>$category){
    $category = htmlspecialchars($category);
    echo "<option value="{$id}">{$category}</option>";
}

Comments

0
foreach($categories as $category => $category_id)

Is what you're looking for.

Comments

0
<select name="category_id">
<option value=""></option>
<?php
$keys = array_keys($categories);
for($i=0; $i<count($categories); $i++)
{?>
    <option value="<?php echo $keys[$i]; ?>"><?php echo $categories[$i]; ?></option>
<?php
}
?>
</select>

Supposing that $categories is the array you have shown above.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.