gavin gavin - 4 months ago 7
PHP Question

The simplest method to POST a single on or off value (PHP)

This should be SO simple so I must be doing something wrong but I have a single checkbox to check whether a value is on or off

<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

Notice: Undefined index: highlight


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, it seems a bit convoluted.

Answer

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';
}