Checkbox Processing in PHP

What’s up with processing checkboxes in PHP?

If I try to simply echo the value of $_POST[“checkbox1”] I get a string of “on”…if the checkbox was selected
If the checkbox was not selected, I get a notice saying the variable is not defined.

Isn’t it supposed to be on/off with PHP? Once I figure out how the data is initially stored in $_POST I should be able to process it all myself, but this initial stage is frustrating me.

Thanks!

You would create the HTML for the form like you would always, under the name field you would add [ ]'s after the name so when and if the user chooses more than one, it will create a multidimensional POST array.

<p>Please select every sport that you play.</p> Soccer: <input type="checkbox" name="sports[]" value="soccer" /><br /> Football: <input type="checkbox" name="sports[]" value="football" /><br /> Baseball: <input type="checkbox" name="sports[]" value="baseball" /><br /> Basketball: <input type="checkbox" name="sports[]" value="basketball" />

So if I came to your site and chose the checkboxes soccer, baseball, and basketball, you would reference the chosen values like so:

[php]$_POST[‘sports’][0] // soccer
$_POST[‘sports’][1] // baseball
$_POST[‘sports’][2] // basketball[/php]

And you could use the foreach statement to decompose the values:

[php]foreach($_POST[‘sports’] as $value)
{
echo $value.’
’;
}[/php]

If someone just chose one, you would just reference the first one as follows

[php]$_POST[‘sports’][0][/php]

I hope this helps you.

Checkbox it’s not a simple input, it’s only send when it’s checked. If it’s not checked, it’s not send.

If you want to check a checkbox in php, you can assummed if it’s not defined $_POST[‘XXX’] (or $_GET[‘XXX’]) this checkbox it’s not checked.

If checkbox are checked, send this value, otherwise it’s not sended.

Sponsor our Newsletter | Privacy Policy | Terms of Service