Question

I noticed that PHP seems to return only values of checked checkboxes. I would like to see a list of checkboxes, not just values of checked checkboxes. Is there a way to detect variables of unchecked boxes?

I asked because I want to be able to update settings. For example, I have a few options that are already checked but if an user decides to uncheck an option, I need to know that unchecked value so I can update the option to be disabled.

Was it helpful?

Solution

I just ran into this problem myself. I solved it by adding a duplicate hidden field with the same name. When the browser sends this information, the second field overrides the first (so ensure that the hidden field comes first).

<input type="hidden" name="foo" value="">
<input type="checkbox" name="foo" value="bar">

If the checkbox is not checked you get:

$_REQUEST[ 'foo' ] == ""

If the checkbox is checked you get:

$_REQUEST[ 'foo' ] == "bar"

OTHER TIPS

This isn't something that can be done purely in PHP.

Browsers only send information about checkboxes if they are checked, if you want to also send information about unchecked checkboxes, you'll have to add hidden fields in the form and use javascript to manage them.

I just stumbled across this problem myself and I sorted it by updating all values in the database to unchecked then re-checking only the ones that are in the POST data, this works fine for me but might not be everyone's cup of tea.

A pure PHP implementation doesn't seem possible, you can try using jQuery/AJAX though.

Suppose you have a 3 checkboxes you want to check, and update_settings is the name of your functions that take the checkbox name as a first argument and a bool value as a second one (activate or not).

Take the following snippet:

$checkboxes = array("checkbox1", "checkbox2", "checkbox3");
foreach($checkboxes as $checkbox){
    $checked = isset($_POST[$checkbox]);
    update_settings($checkbox, $checked);
}

Althouth Peter Kovacs solution it's going to work, I don't think it's practical since you can already check your variables using isset.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top