0

I'm trying to set a variable to true/false based on the value of a checkbox obtained after submitting a form.

Here's the code I have. When the checkbox is checked it works as expected, but when it's not, the variable ends up being empty instead of false.

HTML

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

PHP

if (isset($_REQUEST['checkbox'])) {
    $checkbox = true;
    echo $checkbox; // echoes true
} else {
    $checkbox = false;
    echo $checkbox; // echoes nothing?
}

I'm not sure where the issue is, or what I'm doing wrong.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • give the checkbox a value - the value will show up if the checkbox is checked – Professor Abronsius Aug 10 '20 at 07:19
  • I'm giving the checkbox a value via the `checked` attribute, using `value` yields the same results. The reason I'm using an `if/else` statement server side is because I'm checking whether or not the value shows up rather than if it shows up as true or false. –  Aug 10 '20 at 07:23
  • Just that `echo false` will not show anything, perhaps https://stackoverflow.com/questions/4948663/php-get-bool-to-echo-false-when-false may also help. – Nigel Ren Aug 10 '20 at 07:24
  • Figured the issue thanks to [this question](https://stackoverflow.com/questions/9042002/php-printed-boolean-value-is-empty-why). " A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values". –  Aug 10 '20 at 07:27

0 Answers0