What common mistakes can beginners make when filling selection lists with for loops in PHP?

One common mistake beginners make when filling selection lists with for loops in PHP is not properly initializing the variable used to store the selected option. This can result in unexpected behavior or errors when trying to retrieve the selected value from the list. To solve this issue, make sure to initialize the variable before the loop starts and assign the selected value to it within the loop.

<select name="colors">
    <?php
    $selectedColor = ""; // Initialize the variable
    $colors = ["Red", "Green", "Blue"];

    foreach ($colors as $color) {
        echo "<option value='$color' ";
        if ($selectedColor == $color) {
            echo "selected";
        }
        echo ">$color</option>";
    }
    ?>
</select>