为什么在没有选择它们时,HTTP POST方法的$ _POST超全局数组中缺少表示单选按钮的键?

问题描述:

I've written following PHP code :

<!DOCTYPE HTML>  
<html>
  <head>
  </head>
  <body>  

    <?php
      // define variables and set to empty values
      $name = $email = $gender = $comment = $website = "";

      if ($_SERVER["REQUEST_METHOD"] == "POST") {
        echo "<pre>";
        print_r($_POST);
        echo "</pre>";
        die;  
      }
    ?>

    <h2>PHP Form Validation Example</h2>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
      Name: <input type="text" name="name">
      <br><br>
      E-mail: <input type="text" name="email">
      <br><br>
      Website: <input type="text" name="website">
      <br><br>
      Comment: <textarea name="comment" rows="5" cols="40"></textarea>
      <br><br>
      Gender:
      <input type="radio" name="gender" value="female">Female
      <input type="radio" name="gender" value="male">Male
      <br><br>
      <input type="submit" name="submit" value="Submit">  
    </form>
  </body>
</html>

When I submitted the form without entering data in any of the form firled or selecting any of the two radio buttons that are present on the HTML form I got following result :

Array
(
    [name] => 
    [email] => 
    [website] => 
    [comment] => 
    [submit] => Submit
)

In above result, I could see the names of all input form controls, even the key representing the text-area is also present within the $_POSTarray. The only expected thing that is missing from the above $_POST array output is the key representing the radio buttons 'gender'

This is my doubt. Why it's going missing from the output of $_POST array?

When I fill in the form controls, select any of the radio buttons everything works fine, no issues with it.

Are there any other similar HTML form controls which behave like radio buttons are behaving in above code which I have written?

Please someone clear my doubt and explain me the reason behind this behavior.

Thank You.

Because when you don't select a radio input, no data is sent to the server. As shown in the MDN:

Note: If no radio button is selected when the form is submitted, there is no value submitted to the server to represent the unselected state (e.g., value=unselected); the value is not submitted to the server at all.

Source