Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read if a checkbox is checked in PHP?

How to read if a checkbox is checked in PHP?

like image 346
Thew Avatar asked Oct 04 '22 18:10

Thew


People also ask

How do you check 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.

How check if checkbox is checked?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

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.


2 Answers

If your HTML page looks like this:

<input type="checkbox" name="test" value="value1">

After submitting the form you can check it with:

isset($_POST['test'])

or

if ($_POST['test'] == 'value1') ...
like image 399
m_vitaly Avatar answered Oct 16 '22 07:10

m_vitaly


Zend Framework use a nice hack on checkboxes, which you can also do yourself:

Every checkbox generated is associated with a hidden field of the same name, placed just before the checkbox, and with a value of "0". Then if your checkbox as the value "1", you'll always get the '0' or '1' value in the resulting GET or POST

<input type="hidden" name="foo" value="0" />
<input type="checkbox" name="foo" value="1"> 
like image 119
regilero Avatar answered Oct 16 '22 06:10

regilero