简体   繁体   中英

PHP- Get index/associated value of option selected in dropdown box

I want to show values in a dropdown box (either from an array or database - please advise on which option is method)

Then

when a user selects a value in dropdown box, i want to have and get its associated index value (like 1, 2).

For example: dropdown box shows values:

"Car"
"Bicycle"

If user selects "Car", when i get dropdown selected value, i should get 1, similarly for "Bicycle" i get 2 .. and so on.

Please advise easy and simplest method to implement this

Thanks

You can use two methods:

1) Set up prior to display a code that holds associative array with key -> value ie: 1 => Car (you can keep it in config file if it doesn't change frequently, you can pull it from database or you can keep it in some other form: serialized, file etc.) and use it when the submitted form is being processed.

2) Use array with key and value with the same string ie: Car => Car and when the form is processed you will have value right away. This solution has some limitations and be troublesome with using more words or other characters that need to be sanitized.

I would advise option 1, you will have to set up the list before and use it after form has been processed but it allows more freedom and its less maintenance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM