Reputation: 145
So I have used some code recently and I would like to know how it works completely because I am not a fan of using stuff I don't understand and where I got the code did not show how it worked. What it does is append all the checked checkboxes to the variable $information.
here is the code I used, the submitted form and the php script
<form name="checkboxform" action="" method="post">
<input type="checkbox" name="ninjas[]" value="stuff">stuff<br>
<input type="checkbox" name="ninjas[]" value="more stuff">more stuff<br>
<input type="submit" value="submit" name="submit">
</form>
so when i click submit this function runs
//excuse the ninja naming part, needed to have a laugh cause this was so frustrating :)
function sneakyNinjas() {
$array = $_POST['ninjas'];
$information = "";
foreach ($array as $key => $value) {
$information .= $value;
}
So I get that it loops through each value in the array and that is why I have named them as such.
But the $keys =>$value part is what I don't understand.
How does it determine when the checkbox has been clicked?
Does it use a boolean that is sent with the array?
any help in understanding the process would be greatly appreciated or a link so I can read up on it cause I have found nothing so far, and by all means correct me where I am wrong with anything I said.
Upvotes: 2
Views: 101
Reputation: 685
$_POST is an associative array. It should only be giving you the value where the key is 'ninjas'.
Upvotes: 0
Reputation: 1
I believe that only checked checkboxes are passed when submitting a form. In your loop, the $key is the field name passed and the $value is its value (matching the attributes in you HTML). The unchecked fields shouldn't be there at all (if I remember correctly).
Upvotes: 0
Reputation:
When an HTML form is submitted, only the values for checkboxes that have been checked are submitted. Unchecked or disabled checkboxes are omitted so your array only contains checked values.
Upvotes: 2