How to set an option from multiple options or array with different values to views as selected in select box using PHP

The good news is, this is possible and in PHP is quite simple really. First we put all of our options and their respective values in an array like so:

<?php
$options=array('Extra, Extra small'=>'xxs','Extra small'=>'xs','Small'=>'s','Medium'=>'m','Large'=>'l','Extra Large'=>'xl','Extra, Extra Large'=>'xxl');

Follow this by opening the select box and calling upon the options array in a foreach loop…

echo '<select>';
foreach($options as $view=>$value){

As you may have noticed the array contains fields that look like ‘Large’=>’l’ and the for each loop is calling upon the options as $view=>$value. $view represents the name field, in this case ‘Large’ and $value represents the value field ‘l’. This is important if you expect the user to see different options in the select box than what the values are set at.

Next we create the variable $selected which is going to be used to determine if there is a match between $row[‘value’] and $value…

$selected=($row['value'] == $value)? "selected" : "";

This is the same as using an if and else statement to set the variable, but shorter. The first section after the variable is asking if $row[‘value’] is equal to $value, if it does then $selected=”selected” else (:) $selected is set to blank.

Next we include the options. Because it is in the foreach loop, we only need one line to insert all of the options…

echo '<option '.$selected.' value="'.$value.'">'.$view.'</option>';

Remember the $selected variable in the last step? Each time the foreach loop goes through a section of the options array set at the beginning, it checks to see if $row[‘value’] equals $value. If it does then $selected will be set as selected and that particular option will be the one that is shown on page load. It continues through the rest of the array until all views and values have been scanned and returns their respective options.

Finally we close the foreach loop and the select box…

}
echo '</select>';

And there you have it, an automatic way to make a select box option set as selected. A similar pattern can be used for check-boxes, radio selectors, tabs and more.

The full code…

<?php
$options=array('Extra, Extra small'=>'xxs','Extra small'=>'xs','Small'=>'s','Medium'=>'m','Large'=>'l','Extra Large'=>'xl','Extra, Extra Large'=>'xxl');

echo '<select>';

foreach($options as $view=>$value){
    $selected=($row['value'] == $value)? "selected" : "";
echo '<option '.$selected.' value="'.$value.'">'.$view.'</option>';
}

echo '</select>';

Leave a Comment