Skip to content
Advertisement

Why does PHP’s $_POST variable get values from HTML’s name attribute instead of id attribute?

I understand that when accessing values of HTML form elements in PHP, we must use the name attribute within the $_POST variable. However, I’m not sure I understand why that’s the case. It seems to me like it may have been better for $_POST to use id attributes and take advantage of the insured uniqueness, rather than potentially finding multiple values if more than 1 form elements share the same name. I’m sure there’s a good reason why name attributes are used instead of id, but I haven’t been able to dig that up and curious to understand why.

Simple example:

index.html

<html>
    <form action="./some_script.php" method="post">
        <input type='text' id='text_input_id' name ='text_input_name'>
        <input type='submit'>
    </form>
</html>

some_script.php

<?php
    $value_from_id = $_POST["text_input_id"]; // will be null
    $value_from_name = $_POST["text_input_name"]; // will contain text input from form
?>

Advertisement

Answer

The primary reason is that forms were added to HTML before IDs were.

However, an ID must be unique in an HTML document but a name doesn’t. You can have multiple form controls with the same name.

Sometimes this is required e.g. in order to create a radio group:

<form>
  <input type="radio" name="availability" value="yes" id="availability_yes">
  <label for="availability_yes">Yes</label>

  <input type="radio" name="availability" value="no" id="availability_no">
  <label for="availability_no">No</label>

  <input type="radio" name="availability" value="if need be" id="availability_inb">
  <label for="availability_inb">If Need Be</label>
</form>

and sometimes it is just useful (e.g. when picking from a list of things).

<form>
  <fieldset>
    <legend>Acceptable Colours</legend>
    <input type="checkbox" name="colours[]" value="red" id="colours_red">
    <label for="colours_red">Red</label>

    <input type="checkbox" name="colours[]" value="green" id="colours_green">
    <label for="colours_green">Green</label>

    <input type="checkbox" name="colours[]" value="blue" id="colours_blue">
    <label for="colours_blue">Blue</label>
  </fieldset>
</form>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement