This one puzzled me for some time… may be I’ve overlooked the php documentation, but I couldn’t find how to make use of the standard checkbox and return the selected values as an array from a simple form.
In the end, it turned to be easy. Consider that we have the following form:
<html>
<form action=’somewhere.php’ name=’form1′ action=’POST’>
John <input type=’checkbox’ name=’user’ value=’john’><br>
Sam <input type=’checkbox’ name=’user’ value=’sam’><br>
Marry <input type=’checkbox’ name=’user’ value=’marry’><br>
<input type=’submit’ value=’Delete User’>
You might expect that by submitting this form to the somewhere.php script, the POST variable would be user and the values would be stored in an array. That’s however not happening because what the browser is doing is sending the following as POST (I used FireFox and LiveHeaders plugin to track that down):
user=john, user=’sam’, user=’marry’ …
Great! That looks great and I would too expect to see an array, but that’s not what happens actually. Once submitted the above form will just pass: user=’marry’ and nothing else, regardless if you have checked Sam and John or not. It seems that each time user is set it overrides the previous information.
A quick glance at the php arrays and we have a solution. PHP as well as other languages uses special brackets ([] <- those one) to indicate that a variable is an array. So to achieve our goal we just need to rename the initial form variable from user to user[]. Just like that:
<input type=’checkbox’ name=’user[]‘ value=’john’>
… same for other users ….
If you submit the form now, you will see only one variable in the $_POST array called $user which is actually an array containing the selected users.
Nothing fancy, but as I said in the beginning it puzzled me for some time.