What are the best practices for structuring PHP code when handling form submissions with radio buttons?

When handling form submissions with radio buttons in PHP, it is essential to properly structure your code to handle the selected radio button value. One common approach is to use an if-else statement to check which radio button was selected and process the form data accordingly. It is also recommended to sanitize and validate the input data to prevent security vulnerabilities.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Check if the radio button was selected
    if (isset($_POST["radio_button"])) {
        $selected_option = $_POST["radio_button"];
        
        // Process the form data based on the selected radio button value
        if ($selected_option == "option1") {
            // Code to handle option 1
        } elseif ($selected_option == "option2") {
            // Code to handle option 2
        } else {
            // Handle other cases or show an error message
        }
    } else {
        // Handle case when radio button was not selected
    }
}
?>