How can dynamically generated variables in PHP be effectively utilized to preselect values in HTML elements like radio buttons?
To preselect values in HTML elements like radio buttons using dynamically generated variables in PHP, you can set the 'checked' attribute on the desired radio button based on the dynamically generated variable value. This can be achieved by checking if the variable matches the radio button value and adding the 'checked' attribute if they match.
<?php
// Dynamically generated variable
$selectedValue = "option2";
// Radio button options
$options = array("option1", "option2", "option3");
// Loop through options and create radio buttons
foreach ($options as $option) {
if ($selectedValue == $option) {
echo "<input type='radio' name='option' value='$option' checked> $option <br>";
} else {
echo "<input type='radio' name='option' value='$option'> $option <br>";
}
}
?>