html form get unticked check box - Solved

greg's picture

He has: 1,581 posts

Joined: Nov 2005

I was searching for a way to identify html form check boxes where users DIDN'T tick them. (unticked) I couldn't find any solutions. Maybe I wasn't using great keywords in Google (what are great keywords?)

So I had to set about writing my own solution.
I thought I would post it here as it may help others!
And of course if any one has a better way I would be glad to hear it.

In the HTML check box inputs, you have to use an array as the "name", and importantly you need to have unique keys for each check box input, as the key names are used in the loop to identify if the user ticked the box:
EG

<?php
<input type="checkbox" name="eat[fruit]" value="yes" />
<
input type="checkbox" name="eat[bread]" value="yes" />
?>

Both inputs have same array name (eat) but different keys assigned to the array (fruit and bread).

When the form is posted, make a new array using ALL the key names you KNOW are used in the checkbox names in your form.
Then use that new array to loop all keys.

With each loop, check if the current key from your new array matches a key in the posted array.
If no match then that key value is NO, if it is matched then that key value is YES (or whatever you want).

It’s IMPORTANT when you make the new array to make the keys in that array in the same order as they appear in the html form so the new array keys are in the same order as the POSTed array.
Otherwise the loop wont match them in order and wont work correctly

Here's the full script I made:

The HTML form
(I wrapped it in php code here so it allowed it to be posted)

<?php
<form method="post" action="post_page.php">
eat fruit <input type="checkbox" name="eat[fruit]" value="yes" />
eat bread <input type="checkbox" name="eat[bread]" value="yes" />
eat apples <input type="checkbox" name="eat[apples]" value="yes" />

<
input type="submit" Value="Go">
</
form>
?>

The post_page.php

<?php
//make the array from what the user DID tick
$post_array = $_POST['eat'];

//make a new array
//key names are all the names IN ORDER from each of your check box inputs
$array_keys = array("fruit" => "", "bread" => "", "apples" => "");

//loop using your new array
//the new array key name is checked for a match in the POSTed array
//if a match is found then user must have ticked so value is "yes"
//if no match is found then user didn't tick the box for that input


foreach ($array_keys as $key => $value){
if (
array_key_exists($key, $post_array)){
$new_array[$key]="yes";
}else{
$new_array[$key]="no";
}
}
?>

Your $new_array is now all the values submited fom tickboxes from the form, with the same key names, and for each one the user didnt tick the key is added and a value of “no” inserted.
This makes it simple to insert into a db where user settings is a yes or no.

Or of course you can change what it outputs for the “yes” and “no” as desired.