PHP: Radio button form

This entry is part 44 of 54 in the series PHP Tutorial

We will go through some form related processing with PHP.

You can first copy (double clicking on the code box) the code below to a file called radio.php and save the file in your local web server.

If you are using WAMP server, make sure that WAMP server is started.

Radio Button
$male_status = 'unchecked';
$female_status = 'unchecked';

if (isset($_POST['Submit1'])) {
    $selected_radio = $_POST['gender'];

    if ($selected_radio == 'male') {
        $male_status = 'checked';
    } else if ($selected_radio == 'female') {
        $female_status = 'checked';

<FORM name="form1" method="post" action="radio.php">

    <Input type='Radio' Name='gender' value='male'
        <?php echo $male_status ?>

    <Input type='Radio' Name='gender' value='female'
        <?php echo $female_status ?>

        <Input type="Submit" Name="Submit1" VALUE="Select a Radio Button">


<?PHP if ($male_status == 'checked') {
    echo "Male selected";
if ($female_status == 'checked') {
    echo "Female selected";

You can try to run the form here.

We have put the PHP code in the same script file (radio.php) and so in the form action field, we have action=”radio.php”.

When the form is first submitted, the isset($_POST[‘Submit1’]) is set to 1(true) allowing the if loop to run.

Depending on which button is set, the if loop will set $male_status to 1 or $female_status to 1.

The $male_status or $female_status will allow us to set one of the buttons to checked status by using and echo statement as in <?php echo $male_status ?>.

Series Navigation<< PHP: htmlspecialchars()
PHP: Radio button me >>