How to read if a checkbox is checked in PHP?

PhpHtmlFormsPostCheckbox

Php Problem Overview


How to read if a checkbox is checked in PHP?

Php Solutions


Solution 1 - Php

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') ...

Solution 2 - Php

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"> 

Solution 3 - Php

When using checkboxes as an array:

<input type="checkbox" name="food[]" value="Orange">
<input type="checkbox" name="food[]" value="Apple">

You should use in_array():

if(in_array('Orange', $_POST['food'])){
  echo 'Orange was checked!';
}

Remember to check the array is set first, such as:

if(isset($_POST['food']) && in_array(...

Solution 4 - Php

Let your html for your checkbox will be like

<input type="checkbox" name="check1">

Then after submitting your form you need to check like

if (isset($_POST['check1'])) {

    // Checkbox is selected
} else {

   // Alternate code
}

Assuming that check1 should be your checkbox name.And if your form submitting method is GET then you need to check with $_GET variables like

if (isset($_GET['check1'])) {
     
   // Checkbox is selected
} 

Solution 5 - Php

$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;

Solution 6 - Php

I've been using this trick for several years and it works perfectly without any problem for checked/unchecked checkbox status while using with PHP and Database.

HTML Code: (for Add Page)

<input name="status" type="checkbox" value="1" checked>

Hint: remove checked if you want to show it as unchecked by default

HTML Code: (for Edit Page)

<input name="status" type="checkbox" value="1" 
<?php if ($row['status'] == 1) { echo "checked='checked'"; } ?>>

PHP Code: (use for Add/Edit pages)

$status = $_POST['status'];
if ($status == 1) {
$status = 1;
} else {
$status = 0;
}

Hint: There will always be empty value unless user checked it. So, we already have PHP code to catch it else keep the value to 0. Then, simply use the $status variable for database.

Solution 7 - Php

To check if a checkbox is checked use empty()

When the form is submitted, the checkbox will ALWAYS be set, because ALL POST variables will be sent with the form.

Check if checkbox is checked with empty as followed:

//Check if checkbox is checked    
if(!empty($_POST['checkbox'])){
 #Checkbox selected code
} else {
 #Checkbox not selected code
}

Solution 8 - Php

You can check the corresponding value as being set and non-empty in either the $_POST or $_GET array depending on your form's action.

i.e.: With a POST form using a name of "test" (i.e.: <input type="checkbox" name="test"> , you'd use:

if(isset($_POST['test']) {
   // The checkbox was enabled...

}

Solution 9 - Php

Learn about isset which is a built in "function" that can be used in if statements to tell if a variable has been used or set

Example:

    if(isset($_POST["testvariabel"]))
     {
       echo "testvariabel has been set!";
     }

Solution 10 - Php

Well, the above examples work only when you want to INSERT a value, not useful for UPDATE different values to different columns, so here is my little trick to update:


//EMPTY ALL VALUES TO 0
$queryMU ='UPDATE '.$db->dbprefix().'settings SET menu_news = 0, menu_gallery = 0, menu_events = 0, menu_contact = 0';
$stmtMU = $db->prepare($queryMU);
$stmtMU->execute();
if(!empty($_POST['check_menus'])) {
foreach($_POST['check_menus'] as $checkU) {
try {
//UPDATE only the values checked
$queryMU ='UPDATE '.$db->dbprefix().'settings SET '.$checkU.'= 1';
$stmtMU = $db->prepare($queryMU);
$stmtMU->execute();

} catch(PDOException $e) {
$msg = 'Error: ' . $e->getMessage();}



	}




}

}

<input type="checkbox" value="menu_news" name="check_menus[]" />
<input type="checkbox" value="menu_gallery" name="check_menus[]" />

....

The secret is just update all VALUES first (in this case to 0), and since the

will only send the checked values, that means everything you get should be set to 1, so everything you get set it to 1.

Example is PHP but applies for everything.

Have fun :)

Solution 11 - Php

You can do it with the short if:

$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;

or with the new PHP7 Null coalescing operator

$check_value = $_POST['my_checkbox_name'] ?? 0;

Solution 12 - Php

$is_checked = isset($_POST['your_checkbox_name']) &&
              $_POST['your_checkbox_name'] == 'on';

Short circuit evaluation will take care so that you don't access your_checkbox_name when it was not submitted.

Solution 13 - Php

A minimalistic boolean check with switch position retaining

<?php

$checked = ($_POST['foo'] == ' checked');

?>

<input type="checkbox" name="foo" value=" checked"<?=$_POST['foo']?>>

Solution 14 - Php

<?php

  if (isset($_POST['add'])) {
   
    $nama      = $_POST['name'];
    $subscribe = isset($_POST['subscribe']) ? $_POST['subscribe'] : "Not Checked";

    echo "Name: {$nama} <br />";
    echo "Subscribe: {$subscribe}";
   
    echo "<hr />";   
   
  }
   
?>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" >

  <input type="text" name="name" /> <br />
  <input type="checkbox" name="subscribe" value="news" /> News <br />

  <input type="submit" name="add" value="Save" />

</form>

Solution 15 - Php

<form>
<input type="check" id=chk1 value="1">
<input type="check" id=chk2 value="1">
<input type="check" id=chk3 value="1">
</form>

when you check on chk2 you can see values as:

<?php
foreach($_POST as $key=>$value)
{
	if(isset($key))
		$$key=strip_tags($value);
}
insert into table (chk1,chk2,chk3) values ('','1','');
?>

Solution 16 - Php

in BS3 you can put

  <?php
                  $checked="hola";
                  $exenta = $datosOrdenCompra[0]['exenta'];
                  var_dump($datosOrdenCompra[0]['exenta']);
                  if(isset($datosOrdenCompra[0]['exenta']) and $datosOrdenCompra[0]['exenta'] == 1){

                      $checked="on";

                  }else{
                    $checked="off";
                  }

              ?>
              <input type="checkbox" id="exenta" name="exenta" <?php echo $checked;?> > <span class="label-text"> Exenta</span>

Please Note the usage of isset($datosOrdenCompra[0]['exenta'])

Solution 17 - Php

Wordpress have the checked() function. Reference: https://developer.wordpress.org/reference/functions/checked/

checked( mixed $checked, mixed $current = true, bool $echo = true )

Description Compares the first two arguments and if identical marks as checked

Parameters $checked (mixed) (Required) One of the values to compare

$current (mixed) (Optional) (true) The other value to compare if not just true Default value: true

$echo (bool) (Optional) Whether to echo or just return the string Default value: true

Return #Return (string) html attribute or empty string

Solution 18 - Php

filter_input(INPUT_POST, 'checkbox_name', FILTER_DEFAULT, FILTER_FORCE_ARRAY)

Solution 19 - Php

<?php

if(isset($_POST['nameCheckbox'])){
    $_SESSION['fr_nameCheckbox'] = true;
}

?>

<input type="checkbox" name="nameCheckbox" 

<?php 

if(isset($_SESSION['fr_nameCheckbox'])){
    echo 'checked'; 
	unset($_SESSION['fr_nameCheckbox']);
} 

?>

Solution 20 - Php

you should give name to your input . then which box is clicked you will receive 'on' in your choose method

Array
(
    [shch] => on
    [foch] => on
    [ins_id] => #
    [ins_start] => شروع گفتگو
    [ins_time] => ما معمولاً در چند دقیقه پاسخ میدهیم
    [ins_sound] => https://.../media/sounds/ding-sound-effect_2.mp3
    [ins_message] => سلام % به کمک نیاز دارید؟
    [clickgen] => 
)

i have two checked box in my form name with 'shch' and 'foch'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThewView Question on Stackoverflow
Solution 1 - Phpm_vitalyView Answer on Stackoverflow
Solution 2 - PhpregileroView Answer on Stackoverflow
Solution 3 - Phprybo111View Answer on Stackoverflow
Solution 4 - PhpGautam3164View Answer on Stackoverflow
Solution 5 - PhpHammad KhanView Answer on Stackoverflow
Solution 6 - PhpZEESHAN ARSHADView Answer on Stackoverflow
Solution 7 - PhpandyView Answer on Stackoverflow
Solution 8 - PhpJohn ParkerView Answer on Stackoverflow
Solution 9 - Phpuser2451511View Answer on Stackoverflow
Solution 10 - PhpHiramView Answer on Stackoverflow
Solution 11 - PhpMazzView Answer on Stackoverflow
Solution 12 - PhpMartin ThomaView Answer on Stackoverflow
Solution 13 - Php RemboView Answer on Stackoverflow
Solution 14 - PhpanteloveView Answer on Stackoverflow
Solution 15 - PhpQ.N.AlhalgabiView Answer on Stackoverflow
Solution 16 - PhpElvis TechnologiesView Answer on Stackoverflow
Solution 17 - PhpAliquaView Answer on Stackoverflow
Solution 18 - PhpThowfeekView Answer on Stackoverflow
Solution 19 - PhpGrzegorzView Answer on Stackoverflow
Solution 20 - PhptaymazView Answer on Stackoverflow