How can the PHP code be modified to ensure that the selected font appears at the top of the dropdown list upon page reload?

To ensure that the selected font appears at the top of the dropdown list upon page reload, you can modify the PHP code to reorder the array of fonts based on the selected font. This can be achieved by moving the selected font to the beginning of the array before generating the dropdown list.

<?php
$fonts = array("Arial", "Times New Roman", "Verdana", "Helvetica", "Courier New");
$selected_font = $_POST['font'] ?? 'Arial'; // Get the selected font from the form submission

// Move the selected font to the beginning of the array
if (($key = array_search($selected_font, $fonts)) !== false) {
    unset($fonts[$key]);
    array_unshift($fonts, $selected_font);
}

// Generate the dropdown list with the selected font at the top
echo '<select name="font">';
foreach ($fonts as $font) {
    echo '<option value="' . $font . '"';
    if ($font == $selected_font) {
        echo ' selected';
    }
    echo '>' . $font . '</option>';
}
echo '</select>';
?>