PHP: checkboxes and name

I am writing, for the first time in PHP, a script to handle a POSTED form containing checkboxes.

As you know, the flags are grouped using the same name, and when several values ​​appear $ _POST ["some_name"] should be stored in an array.

I tested, but instead of the expected array, I got one single value - the value of the last marked item.

At this point, somewhat puzzled, I look at some kind of document to find out that with PHP, the cell name should end in [] . This is true? What crazy relationship exists between the HTML form and the script that processes it? Suppose I don’t have access to HTML field names? Suppose, as in my case, I have every reason not to change my naming scheme only for some obscure nonsense.

Now it seems that there is at least one solution to the problem: PHP: getting the value of the flags when the name does not have an array

I would like to know if there is a really easy way to do without these crazy brackets and, by the way, your opinion on this issue? Was I really shocked?

EDIT: Well, I can certainly get around this problem, but I was hoping to raise some (minor) fundamental points regarding some kind of “non-separation of problems” between HTML and PHP. Obviously, none of the PHP business like HTML code should be written.

+4
source share
3 answers

In your html code for checkboxes:

name="mycheckboxname[]"

0
source

What is your good reason not to include [] in your naming scheme? I do not think this is particularly shocking. As for PHP, perhaps you really expected to get only the value from the last element with this particular name.

There are several alternatives, such as the one you included in your question, or choosing values ​​using some kind of javascript cheat, but I don’t think it will be easier than simply adding brackets to the name of your checkboxes.

0
source

You should try

 <input type="checkbox" name="mycheckbox[]" value="Male" /> <input type="checkbox" name="mycheckbox[]" value="Female" /> In php side, $myCheckBoxCollection = $_REQUEST['mycheckbox']; 
0
source

All Articles