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

JavaScript

some_script.php

JavaScript

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:

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement