How can PHP be used to save and retrieve user selections from a dynamically generated drop-down list?
To save and retrieve user selections from a dynamically generated drop-down list in PHP, you can use sessions to store the selected value and retrieve it when needed. When the user selects an option from the drop-down list, you can store the value in a session variable. Then, when the page is reloaded or navigated to another page, you can retrieve the stored value from the session and pre-select the option in the drop-down list accordingly.
<?php
session_start();
// Check if a selection has been made
if(isset($_POST['dropdown'])){
$_SESSION['selected_option'] = $_POST['dropdown'];
}
// Generate a dynamically populated drop-down list
$options = array('Option 1', 'Option 2', 'Option 3');
echo '<form method="post">';
echo '<select name="dropdown">';
foreach($options as $option){
$selected = ($_SESSION['selected_option'] == $option) ? 'selected' : '';
echo '<option value="'.$option.'" '.$selected.'>'.$option.'</option>';
}
echo '</select>';
echo '<input type="submit" value="Submit">';
echo '</form>';
?>