-2

I have to pass either an ON or OFF value in php. Is a single checkbox to check whether a value is on or off the simplest method? I have:

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

and when it is posted, if it is checked I get the value 'on' but if it is not checked I get an error of 'Undefined index'

Now I have tried testing whether it is empty or isset but I would like to know if this is the correct method for passing a boolean value.

gavin stanley
  • 1,082
  • 2
  • 13
  • 28

2 Answers2

3

Unchecked boxes are simply not sent in POST|GET

You can just use the isset() function, its value is irrelevant:

if (isset($_POST['highlight'])) {
    echo 'it was checked';
} else {
    echo 'it was not checked';
}
scrowler
  • 24,273
  • 9
  • 60
  • 92
1

You can do like this:

 $cheeked = isset($_POST['highlight'])?1:0;

$cheeked will be 1 if checked and 0 if not.

Amazone
  • 426
  • 4
  • 14