How can PHP be used to preselect dropdown options based on data read from a text file?
When reading data from a text file in PHP to preselect dropdown options, you can store the selected value in a variable and compare it with the options in the dropdown. If the value matches, you can use the "selected" attribute in the HTML option tag to preselect it.
<?php
// Read data from text file
$selected_option = trim(file_get_contents('selected_option.txt'));
// Dropdown options
$options = ['Option 1', 'Option 2', 'Option 3'];
// Display dropdown with preselected option
echo '<select name="dropdown">';
foreach ($options as $option) {
if ($option == $selected_option) {
echo '<option value="' . $option . '" selected>' . $option . '</option>';
} else {
echo '<option value="' . $option . '">' . $option . '</option>';
}
}
echo '</select>';
?>
Related questions
-
PHP session variables database entries
-
var_dump echo debugging
-
PHP PDF generation output handling