How to check if a checkbox is checked with PHP?

Asked

Viewed 64,831 times

24

How to check if a checkbox is checked when a form is submitted?

8 answers

30


If your HTML page looks like this:

<input type="checkbox" name="meucheckbox" value="umvalorqualquer">

When sent, if the check box is not checked, there is no variable meucheckbox, his value is NULL. If it is marked it receives the variable meucheckbox and its value will be any value.

On the PHP page you can check as follows if the form is submitted via POST:

if(isset($_POST['meucheckbox']))
{
    echo "checkbox marcado! <br/>";
    echo "valor: " . $_POST['meucheckbox'];
}
else
{
    echo "checkbox não marcado! <br/>";
}

If the form is submitted via GET:

if(isset($_GET['meucheckbox']))
{
    echo "checkbox marcado! <br/>";
    echo "valor: " . $_GET['meucheckbox'];
}
else
{
    echo "checkbox não marcado! <br/>";
}


If the checkbox is checked, the result will be:

checkbox marcado!
valor: umvalorqualquer

If the checkbox is not checked, the result will be:

checkbox não marcado!

10

A checkbox in an HTML form is only sent if it is marked, so just check if it is present in the variables $_GET or $_POST.

Example with method post:

isset($_POST['minhacheck'])

Example with method get:

isset($_GET['minhacheck'])

In this case, the HTML would be:

<input type="checkbox" name="minhacheck" value="valor">
  • Thanks utluiz, I was in doubt if he sends even if not marked, took my grateful doubt!

6

  //Aqui verifico se o post do checkbox me retorna um valor verdadeiro ou falso (true ou false)
  $checkbox = $_POST["CheckBox"] ? "Marcado (true)" : "Desmarcado (false)";
  echo $checkbox; // Imprimo a resposta.
  • Hiago, if possible develop the answer by adding a comment to your code and about why this code solves the problem.

  • Thank you Sergio, I commented the code sorry for the lack of attention.

  • 1

    Great! + 1, so it’s much more useful for those who can’t read what the code does.

4

One thing you may also have that I haven’t seen is if you don’t pass any value, for example:

<input type="checkbox" name="meu_checkbox" checked="checked">

for example, if you send by post, in php you will get it like this

if (isset($_POST['meu_checkbox']) && $_POST['meu_checkbox'] == 'on')
{
    echo "Meu Checkbox está marcado";
}

You need to check if there is the value because if the user does not check the checkbox will not be passed anything and will give you an error, and when you pass no value is passed with value on

The error you will give if you do not check if it exists (isset) is this:

PHP Error was encountered

Severity: Notice

Message: Undefined index: meu_checkbox

3

In the array of $_REQUEST (I don’t know if your form method is GET or POST), just check if your checkbox name key is there, with the corresponding value.

  • It only sends when it’s checked?

  • I think it’s interesting that you post the code with your form so we can help you better.

  • 1

    That’s right, the value is only sent when it is checked. What you can do is give the checkbox the name of checkboxes[] (for example) and see the values that will be inside the array checkboxes in the values of $_REQUEST.

  • $_REQUEST should even exist. If it is POST, $_POST. If it is GET, $_GET. If it is COOKIE, $_COOKIE. Not only is it wrong to use it, but it’s also wrong to use it.It prevents the application from reusing the same identification keyword in the superglobal for different scenarios.

  • I set an example with $_REQUEST because I didn’t know the person was using GET or POST. In fact one should take the variables with $_GET or $_POST, respectively.

  • Yeah, yeah, I just mentioned it to reinforce.

Show 1 more comment

3

The big idea is in the form to name the checkbox as vector, as the example below:

<table border="0" width="100%">
<tr>
<td class="menu" width="130">
Treinamentos:
</td>
<td class="menu">
<nobr><input type="checkbox" name="ckbTreinamentos[]" value="I"> Internet</nobr>
</td>
<td class="menu">
<nobr><input type="checkbox" name="ckbTreinamentos[]" value="U"> URA</nobr>
</td>
<td class="menu">
<nobr><input type="checkbox" name="ckbTreinamentos[]" value="P"> POS</nobr>
</td>
<td class="menu">
<nobr><input type="checkbox" name="ckbTreinamentos[]" value="T"> TEF</nobr>
</td>
<td class="menu">
<nobr><input type="checkbox" name="ckbTreinamentos[]" value="C"> Celular</nobr>
</td>
<td class="menu">
<nobr><input type="checkbox" name="ckbTreinamentos[]" value="F"> Fechamentos</nobr>
</td>
</tr>
</table>

Then at the time of $_REQUEST['] you can mount a foreach that can be played in a string, as the example below:

if (isset($_REQUEST['ckbTreinamentos'])) {          
        $qt = count($_REQUEST['ckbTreinamentos']);
        $k = 1;         
        foreach ($_REQUEST['ckbTreinamentos'] as $treinamento){             
            $v = "";
            if($k < $qt) {
                $v = ", ";
            }
            $comp .= $treinamento.$v;
            $k++;
        }
        return $comp;
    } else {
        $comp = null;
    }

2

Work with checkbox with PHP is quite annoying because of this limitation of the program receiving the value only if it has been marked.

But that limitation only becomes noticeably annoying when you have many checkboxes in the same form, for example in a user access control permissions editor, where it would be necessary to repeat dozens of times a ternary or create a loop check in order to simplify the process at the cost of earning cyclomatic complexity

Anyway... For these very specific cases you can modify the HTML by defining a field of type Hidden of the same name as the checkbox:

<input type="hidden" name="meucheckbox" value="0" />
<input type="checkbox" name="meucheckbox" value="1" />

Given the vertical processing, if the checkbox is not checked, you still have, for example, a $_POST['meucheckbox'] 0 (zero) and, if marked, the entry shall be replaced in the superglobal by the value due.

1

If in your form, you have for example:

<input type="checkbox" name="status" value="ativo">

When submitting the form, if the field is NOT marked, it will not be sent to your server.

Soon it would be like you trying to access an index in an array without it existing or accessing an index name in a non-existent associative array.

If it is marked you can access its value normally as in an array.

On the PHP page you will receive the data sent by the form:

Global variables may be used: $_POST, $_GET or $_REQUEST;

<?php
   //Verificando se o "índice associativo 'status'" foi enviado pelo formulário 
   $statusRecebido = (isset($_REQUEST['status']))?$_REQUEST['status']:'inativo';

   //Se o checkbox foi marcado, virá o valor contido no seu atributo 'value', ou seja, 'ativo'. 
   //caso não venha será atribuído o valor 'inativo' por exemplo.

   echo $statusRecebido."<br/>";

I hope I’ve helped you better understand.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.