315

How to read if a checkbox is checked in PHP?

Thew
  • 15,789
  • 18
  • 59
  • 100
  • 18
    This question actually means "*was* checked" (when the form was submitted). PHP determining if a checkbox **is** checked would require an Ajax call once the element was toggled. – rybo111 Jul 14 '18 at 13:59

21 Answers21

404

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') ...
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
m_vitaly
  • 11,856
  • 5
  • 47
  • 63
  • 68
    Checkboxes can also have value `on`, when they are checked. Therefore for compatibility it's easier just to use `isset($_POST['checkboxName'])`. – Damiqib Dec 29 '10 at 14:09
  • 15
    The "on" value may be supported by some browsers when value attribute is not set, but in general it is better to set the value attribute and to check for it on submit. – m_vitaly Dec 29 '10 at 14:59
  • 3
    Does the 'Value1' change if the box is checked? – MoralCode Nov 18 '14 at 23:08
  • 14
    @Developer_ACE Unless I'm misunderstanding you, the value in this example would be `value1` if the checkbox is checked. If it's not checked, `$_POST['test']` would simply not exist. – rybo111 May 23 '15 at 14:58
  • if using serialize to submit do this. var checkbox1_data = $("#checkboxinput_id").prop("checked")==false?"0":"1"; var data = $("#formveri").serialize()+"&a="+checkbox1_data; – matasoy Mar 30 '21 at 07:00
123

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"> 
Chuck Le Butt
  • 47,570
  • 62
  • 203
  • 289
regilero
  • 29,806
  • 6
  • 60
  • 99
  • I also noticed about that, but I feel safe to use it: Zend Framework does it too! – hpaknia Sep 03 '14 at 10:49
  • This is interesting. But is there a tiny possibility that the user agent might submit the first value instead of the last, assuming the checkbox is checked? – rybo111 Dec 09 '15 at 21:47
  • @rybo111, for the user agent i don't think so, but for a custom javascript form parser you should take care. – regilero Dec 09 '15 at 21:52
  • Sorry, could someone explain me how does it work? I didn't understand. Why that hidden field if only the last value is always submitted (the `input[type="checkbox"]`'s one)? – tonix Jan 31 '16 at 20:34
  • 12
    when the checkbox is unchecked it's not transmitted in the post (so only the hidden is transmitted). When it's checked it is transmitted, and will overwrite the hidden value. – regilero Feb 01 '16 at 21:07
  • 1
    i really cant belive this is working. What a damn situation. Checkboxes is wrong designed so. Thank u for your answer. – matasoy Mar 30 '21 at 06:45
60

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(...
rybo111
  • 12,240
  • 4
  • 61
  • 70
  • checkboxes as an array and `foreach ($_POST['food'] as $selected_food)` to work on checked one is nice, thanks – bcag2 May 04 '20 at 13:02
43

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
} 
GautamD31
  • 28,552
  • 10
  • 64
  • 85
27
$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;
TheTechGuy
  • 16,560
  • 16
  • 115
  • 136
10

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.

Brian C
  • 837
  • 1
  • 10
  • 20
ZEESHAN ARSHAD
  • 566
  • 5
  • 11
  • 1
    this is the really good form to do this in pure simple php. but have to note that the value of a checkbox is string on when it is activated an a inexisting value if it is checked. – Elvis Technologies Nov 24 '18 at 05:07
7

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
}
ProGrammer
  • 976
  • 2
  • 10
  • 27
andy
  • 341
  • 3
  • 11
3

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;
Mazz
  • 1,859
  • 26
  • 38
3

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

}
John Parker
  • 54,048
  • 11
  • 129
  • 129
2

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!";
     }
Venkateshwaran Selvaraj
  • 1,745
  • 8
  • 30
  • 60
user2451511
  • 117
  • 1
  • 1
  • 8
2

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 :)

Hiram
  • 2,679
  • 1
  • 16
  • 15
1
$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.

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
1

A minimalistic boolean check with switch position retaining

<?php

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

?>

<input type="checkbox" name="foo" value=" checked"<?=$_POST['foo']?>>
Rembo
  • 11
  • 2
  • 2
    When giving an answer it is preferable to give [some explanation as to WHY your answer](http://stackoverflow.com/help/how-to-answer) is the one. This is especially true when answering a *VERY* old post 11 other answers. – Stephen Rauch Feb 21 '17 at 01:23
  • It's good you recognize the need for the checkbox to retain its state. However, your code to do this is not correct. – Vern Jensen Jul 05 '17 at 20:49
1
<?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>
antelove
  • 3,216
  • 26
  • 20
1
<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','');
?>
0

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

0

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

Aliqua
  • 723
  • 7
  • 21
0

i have fixed it into a PHP form with a checkbox

$categories = get_terms( ['taxonomy' => 'product_cat', 'hide_empty' => false] ); foreach ($categories as $categorie) { echo "<input type="checkbox" value="$categorie->term_taxonomy_id" name="catselected[]"> $categorie->slug"; }

This way i add it to the Woocommerce tabel. wp_set_post_terms( $product_id, $_POST['catselected'], 'product_cat' );

Marcel Kraan
  • 91
  • 1
  • 9
-1

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

Thowfeek
  • 137
  • 1
  • 5
-3
<?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']);
} 

?>
rbr94
  • 2,227
  • 3
  • 23
  • 39
  • 1
    Welcome to Stack Overflow! While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. **Flaggers / reviewers:** [For code-only answers such as this one, downvote, don't delete!](//meta.stackoverflow.com/a/260413/2747593) – Scott Weldon Oct 21 '16 at 22:54
-3

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'

B001ᛦ
  • 2,036
  • 6
  • 23
  • 31
taymaz
  • 17
  • 4