Getting Selected Option From PHP Select List

light_bulb_large

Let’s say you have a php select box that is dynamically generated through your php loop. You want to make sure that the selected option is always displayed even after reload.

Here is an example of a basic dynamic list:

However when the page loads, you cannot tell which color was selected and aren’t sure where to put the html ‘selected’ value because the code simply ran through the colors loop.

Solution:

You can find the value by using a php array search, and by adding this ternary statement.

Voila you will have the selected option displayed properly.

Your code now becomes

By using a ternary statement or if statement we compare the index of the string in array, with the index of the iterator.

So we did an array search to find the position of $selected_color in the colors array. Therefore, a search of
value2 will return index 2. So in general, if a search of $selected_value ever matches the loop index we know we can echo ‘selected’.

 

Leave a Reply

Your email address will not be published. Required fields are marked *