How to set an option from multiple options or arra

2019-01-12 12:51发布

An option value is taken from the database and included in a select box along with other options. How can I set the value taken from the database as selected?

The value from the database is set as $row['value'] and equals s. In HTML the options look like so...

<select name="select">
<option value='xxs'>Extra, Extra small</option>
<option value='xs'>Extra small</option>
<option value='s'>Small</option>
<option value='m'>Medium</option>
<option value='l'>Large</option>
<option value='xl'>Extra Large</option>
<option value='xxl'>Extra, Extra small</option>
</select>

What I want is the $row['value'] (Small) option to be displayed on page load... Is this possible?

2条回答
Lonely孤独者°
2楼-- · 2019-01-12 13:16

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>';
查看更多
做个烂人
3楼-- · 2019-01-12 13:31

Given this array, and this value to be the selected value...

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

$selected = 'm';  // $selected can be swapped for $row['value'] as in the OP 

There are several ways to dynamically construct the option tags inside of a <select> and set the selected attribute on one of them.

First the one-liner inside a foreach loop:

echo "<select name=\"select\">";
    foreach($options as $text=>$value){
        echo "<option value=\"$value\"" , ($selected == $value ? " selected" : "") , ">$text</option>";
    }
echo "</select>";

This code block uses a ternary conditional operator aka conditional operator aka shorthand if/else aka inline conditon. Go here for further reading and examples.

  • By using double quotes " you avoid having to toggle back and forth between literal strings and variables. *You will have to escape double quotes that are nested inside of the string by prepending \. *Variables can be wrapped in curly brackets to isolate their variable name from the surround text. *Single quotes will not echo the value of the variable.) For continued read about quoting: reference

  • By using , (commas) instead of . (dots) to concatenate the string, performance is increased. one benchmark

  • By only adding a space before the selected attribute in the true condition (versus adding the space outside the condition on every iteration), you avoid creating unnecessary spaces inside your tag.

  • By using an inline condition statement, you avoid unnecessarily declaring a variable into the global scope. If you declare the selected string as a variable, as @independent.guru does, it will be declared/overwritten and used only once on every iteration; this can only decrease performance.

Each programmer will have their own preferences about "readability", "brevity", "consistency", and "performance" and may elect to construct their html using any mixture of the above techniques.

As a general rule, I don't bother to declare a variable that I will only use once. In my personal preference hierarchy, brevity, consistency, and performance always come before readability.

Some of the above points may seem like micro-optimizations, but for a canonical question, it is reasonable to include discussion on performance as any of the listed methods may be copy-pasted directly into projects.

If the first code block was too compact, here are two other versions that spread out the method over multiple lines without generating any extra variables:

Separated shorthand if/else syntax:

echo "<select name=\"select\">";
    foreach($options as $text => $value){
        echo "<option value=\"$value\"";
            echo $selected == $value ? " selected" : "";
        echo ">$text</option>";
    }
echo "</select>";

Standard if conditional:

echo "<select name=\"select\">";
    foreach($options as $text => $value){
        echo "<option value=\"$value\"";
            if($selected == $value){
                echo " selected";
            }
        echo ">$text</option>";
    }
echo "</select>";

All of the above versions of the same method will create this rendered html:

When the page is loaded:

enter image description here

When the select element is opened:

enter image description here

The source code will look like this:

<select name="select"><option value="xxs">Extra, Extra small</option><option value="xs">Extra small</option><option value="s">Small</option><option value="m" selected>Medium</option><option value="l">Large</option><option value="xl">Extra Large</option><option value="xxl">Extra, Extra Large</option></select>

This is the source code tabbed out for easier reading:

<select name="select">
    <option value="xxs">Extra, Extra small</option>
    <option value="xs">Extra small</option>
    <option value="s">Small</option>
    <option value="m" selected>Medium</option>
    <option value="l">Large</option>
    <option value="xl">Extra Large</option>
    <option value="xxl">Extra, Extra Large</option>
</select>
查看更多
登录 后发表回答