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:

<?php

$colors = fetchColors() //return array of colors array ("red","blue","green","purple")
$selected_color = fetSelectedColor(); //returns string of selected color
?>

<select name="selectColor">
  <?php foreach ($colors as $color): ?> <option value="<?php echo $color;?>"> <?php echo $color; ?> </option> <?php endforeach ?>
</select>

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.

<?php echo (array_search($selected_color, $colors) == $key) ? 'selected' : ''?>

Voila you will have the selected option displayed properly.

Your code now becomes

<?php

$colors = fetchColors() //return array of colors array ("red","blue","green","purple")
$selected_color = fetSelectedColor(); //returns string of selected color

<select name="selectColor">
  <?php foreach ($colors as $key=>$value): ?> <option value="<?php echo $value;?>" <?php echo (array_search($selected_color, $colors) == $key) ? 'selected' : ''?>> <?php echo $value; ?> </option> <?php endforeach ?>
</select>

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

<select>
      <option value="value0"> //index is 0 </option>
      <option value="value1"> //index is 1 </option>
      <option value="value2"> //index is 2 </option>

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’.

One thought on “Getting Selected Option From PHP Select List

  1. Hi, How can I make it so that more than one options can be selected?

    for example:

    $selected_color = array(“red”, “blue”);

    Red
    Grey
    Blue
    Yellow

    Regards

Leave a Reply

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