Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I get all checkbox variables even if not checked from HTML to PHP?

Tags:

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.

like image 760
netrox Avatar asked Dec 22 '09 03:12

netrox


People also ask

How can I get multiple checkbox values in PHP if checked?

To get all the values from the checked checkboxes, you need to add the square brackets ( [] ) after the name of the checkboxes. When PHP sees the square brackets ( [] ) in the field name, it'll create an associative array of values where the key is the checkbox's name and the values are the selected values.

How can I get checkbox data in PHP?

In order to get the checkbox values, you can use the foreach() method. Note: The foreach() method functions by looping through all checked checkboxes and displaying their values.

How do you check if a checkbox is checked or not in PHP?

The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.


1 Answers

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" 
like image 149
Peter Kovacs Avatar answered Oct 01 '22 17:10

Peter Kovacs