Home >Backend Development >PHP Tutorial >How Can I Pre-Select an Option in a Dropdown Box Using PHP?
How to Pre-Select an Option in a Dropdown Box Using PHP
In HTML, you can set the selected item in a dropdown box using the selected attribute. However, in the code provided, the selected attribute is being set using a PHP variable, which can be confusing.
To pre-select an item in a dropdown box based on a database value, you need to set the selected attribute of the correct option tag to "selected."
<code class="html"><option value="January" selected="selected">January</option></code>
In the PHP code, you would assign the selected value to the appropriate option tag as follows:
<code class="php"><option value="January"<?php echo $row['month'] == 'January' ? ' selected="selected"' : ''; ?>>January</option></code>
This code checks if the value of $row['month'] is equal to 'January'. If it is, the selected="selected" attribute is added to the option tag. Otherwise, the empty string (``) is added.
It's generally considered better practice to create an array of values and loop through it to create a dropdown. This makes the code easier to maintain and understand.
The above is the detailed content of How Can I Pre-Select an Option in a Dropdown Box Using PHP?. For more information, please follow other related articles on the PHP Chinese website!