Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

An easy question:

How do I check in PHP whether a checkbox is checked or not?

share|improve this question

5 Answers

up vote 15 down vote accepted

If the checkbox is checked you the value of it will be passed. Otherwise it won't.

if (isset($_POST['mycheckbox'])) {
    echo "checked!";
}
share|improve this answer

http://www.html-form-guide.com/php-form/php-form-checkbox.html

This covers checkboxes, and checkbox groups.

share|improve this answer

Try this

<form action="form.php" method="post">
    Do you like stackoverflow?
    <input type="checkbox" name="like" value="Yes" />
 <input type="submit" name="formSubmit" value="Submit" />
</form>
<?php
    if(isset($_POST['like'])
    {
        echo "You like Stackoverflow.";
    }
    else
    {
        echo "You don't like Stackoverflow.";
    }   
?>

Or this

<?php
    if(isset($_POST['like']) && 
    $_POST['like'] == 'Yes') 
    {
        echo "You like Stackoverflow.";
    }
    else
    {
        echo "You don't like Stackoverflow.";
    }   
?>
share|improve this answer

you can check that by either isset() or empty() (its check explicit isset) weather check box is checked or not

for example

  <input type='checkbox' name='Mary' value='2' id='checkbox' />

here you can check by

if (isset($_POST['Mary'])) {
    echo "checked!";
}

or

if (!empty($_POST['Mary'])) {
    echo "checked!";
}

the above will check only one if you want to do for many than you can make an array instead writing separate for all checkbox try like

<input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
<input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
<input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />

php

  $aDoor = $_POST['formDoor'];
  if(empty($aDoor))
  {
    echo("You didn't select any buildings.");
  }
  else
  {
    $N = count($aDoor);
    echo("You selected $N door(s): ");
    for($i=0; $i < $N; $i++)
    {
      echo($aDoor[$i] . " ");
    }
  }
share|improve this answer

I did a blog post on determining if a checkbox is checked or not, in the case you want the value from either case to be in your $_POST array.

Check out http://www.martinbean.co.uk/web-development/the-check-box-input-element/ for a more in-depth explanation.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.