What is the recommended approach for handling preselection of options in radio buttons and combo boxes in PHP to ensure XHTML standard compliance?
When preselecting options in radio buttons and combo boxes in PHP to ensure XHTML standard compliance, it is recommended to use the selected attribute for radio buttons and the selected option tag for combo boxes. This ensures that the preselected option is marked as selected in the HTML output.
<?php
$selectedOption = "option2"; // This is the value of the preselected option
// Radio buttons
$option1Checked = ($selectedOption == "option1") ? "checked" : "";
$option2Checked = ($selectedOption == "option2") ? "checked" : "";
$option3Checked = ($selectedOption == "option3") ? "checked" : "";
echo "<input type='radio' name='option' value='option1' $option1Checked> Option 1";
echo "<input type='radio' name='option' value='option2' $option2Checked> Option 2";
echo "<input type='radio' name='option' value='option3' $option3Checked> Option 3";
// Combo box
echo "<select name='option'>";
echo "<option value='option1' " . (($selectedOption == "option1") ? "selected" : "") . ">Option 1</option>";
echo "<option value='option2' " . (($selectedOption == "option2") ? "selected" : "") . ">Option 2</option>";
echo "<option value='option3' " . (($selectedOption == "option3") ? "selected" : "") . ">Option 3</option>";
echo "</select>";
?>