Page 1 of 1

Getting itemindex of a "drop down" list

Posted: Tue Mar 11, 2003 9:32 am
by Zomis
Hi all!
I'm new to this forum, and also quite new to php (only worked with it for 2½ months).
Ok, enough about me now ;)
Here's my problem:

I don't have any code to demonstrate my problem with, but I hope you can understand me anyway.
I have a SELECT form item (a.k.a. drop-down list/combobox/listbox)
And let's say that this select box has 10 items, like these:
Sugar
Milk
More milk
Some other kind of milk
Milk
Nice Sugar

let's say I choose "Milk", when the form process this to my PHP script, the script only gets "Milk" in the variable, but how can I find out inside the script if I choosed the first Milk or the second Milk?
Should I add an itemindex to each item so it says "1: Milk" and "4: Milk" instead of "Milk"?

hope you understand

Posted: Tue Mar 11, 2003 9:36 am
by twigletmac
Is the select box hardcoded (ie. every option coded into a static page) or is it dynamic (e.g. from a database).

Mac

Posted: Tue Mar 11, 2003 9:39 am
by Zomis
dynamic, I read it from a file, but later I'm thinking of changing it so I read from a database (mySQL) instead.

Posted: Tue Mar 11, 2003 10:03 am
by twigletmac
If you've got something like this in your file:

Code: Select all

Sugar 
Milk 
More milk 
Some other kind of milk 
Milk 
Nice Sugar
I'd change it to:

Code: Select all

1|Sugar 
2|Milk 
3|More milk 
4|Some other kind of milk 
5|Milk
6|Nice Sugar
and then do something like:

Code: Select all

<select name="select1">
<?php
$lines = file($selectinfofile);
foreach ($lines as $info) {
    $optioninfo = explode('|', $info);
    echo '<option value="'.$optioninfo[0].'">'.$optioninfo[1].'</option>';
}
?>
</select>
Then in the processing script you can read from the file again to determine which option had been chosen.

Code: Select all

<?php
$lines = file($selectinfofile);
foreach ($lines as $info) {
    $optioninfo = explode('|', $info);
    if ($optioninfo[0] == $_POST['select1'];
        $option_num = $optioninfo[0];
        $infoselected = $optioninfo[1];
        break;
    }
}
echo 'You selected option number '.$option_num.': '.$infoselected;
?>
That's one way, there are others and it'll depend of course on how your text file is already formatted.

Mac

Posted: Tue Mar 11, 2003 10:09 am
by Zomis
wow, thanks a lot!
I didn't thought that I could use the value statement in an option
:D
Thanks for your help!