Jump to content

Checkbox shows as undefined when unchecked


nibble

Recommended Posts

Hi... I'm new to PHP or any web coding and need some help....

 

I'm using.. Windows > WAMP > Apache | PHP | MySQL

 

I'm trying to take a user input using check box and POST method. using the following code

<form action="abc.php" method="post">
One: <input type="checkbox" name="checkbox" />
<input type="submit"/>

 

When checked I get a value "on" echoed on using the >> echo $_POST["checkbox"]; << and when unchecked I get >> Undefined index: checkbox in... << message

 

Any help is greatly appreciated.

if(isset($_POST['checkbox']) && !empty($_POST['checkbox'])) {
    // checkbox is checked
}

 

You can just do this:

if(!empty($_POST['checkbox'])) {
    // checkbox is checked
}

 

It's impossible to have isset($_POST['checkbox']) == false and !empty($_POST['checkbox']) == true simultaneously.

But when you don't have the key checkbox won't it throw a notice for undefined index?

 

Edit: answered my own question. I didn't know that empty wouldn't throw a notice

empty() is the opposite of (boolean) var' date=' except that no warning is generated when the variable is not set.[/quote']

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.