Saska
Saska

Reputation: 1021

Checkboxes in PHP

I have HTML

<td><input value="on" checked="checked" name="checkbox1[0]" type="checkbox"></td>
<td><input value="on" checked="checked" name="checkbox2[0]" type="checkbox"></td>
<td><input value="on" checked="checked" name="checkbox3[0]" type="checkbox"></td>

and function

function checkbox_verify($_name) {
    $result = 0;
    if(isset($_REQUEST[$_name])) {
        if($_REQUEST[$_name] == 'on') {
            $result = 1;
        } else {
            $result = 0;
        }
    }
    return $result;
}

using:

$tmp = checkbox_verify("checkbox[$k]") . " " . checkbox_verify("checkbox2[$k]"). " " . checkbox_verify("checkbox3[$k]");

I want to just check checkbox - checked it or not. But everytime result is "0"

Upvotes: 0

Views: 132

Answers (2)

ThiefMaster
ThiefMaster

Reputation: 318488

PHP automatically converts foo[bar]-style field names into an array. So you will need to check for $_REQUEST['checkbox1'][0]. Since a checkbox only has a value if checked the following check is sufficient:

if(isset($_REQUEST['checkbox1'][0])) {
    // do stuff
}

Another option would be renaming your checkboxes to not include brackets. Then you could simply check $_REQUEST['name-of-the-checkbox'].

Upvotes: 2

xdazz
xdazz

Reputation: 160833

Remove [0] of the name:

<td><input value="on" checked="checked" name="checkbox1" type="checkbox"></td>
<td><input value="on" checked="checked" name="checkbox2" type="checkbox"></td>
<td><input value="on" checked="checked" name="checkbox3" type="checkbox"></td>

Then you could check it just with isset:

function checkbox_verify($_name) {
  return isset($_REQUEST[$_name]);
}

Upvotes: 0

Related Questions