stef
stef

Reputation: 27799

PHP $_POST array for unchecked checkboxes

If I have a form with two checkboxes that have have the same array as name attribute

name="1_1[]"

and neither of those checkboxes is ticked, is there any way I can know they were present in the form? These fields are not being sent through the $_POST array if they are unchecked.

I'm asking this cause these name values are being generated dynamically, I don't always know what they are and I have to validate them (make sure at least one of the two is checked).

Do I have to start using hidden fields to send the name attribute values through, or is there a better way?

Upvotes: 2

Views: 3361

Answers (2)

markus
markus

Reputation: 40685

The fact that they're not in the $_POST array means you can use isset() to see if they've been set.

If you've got two checkboxes and one needs to be set at least, you could do:

$missingValue = TRUE;

if(isset($_POST['checkbox_foo'] || isset($_POST['checkbox_bar'])
{
    $missingValue = FALSE;
}

If that's not good enough, you'll have to go with hidden fields.

Upvotes: 1

Matti Virkkunen
Matti Virkkunen

Reputation: 65176

Using a hidden field would probably be the most sensible way if you really can't get to the data on the receiving page, if you want to keep on using checkboxes. You can't get a checkbox to send a value if it's unchecked, that's how they work.

On the other hand, the receiving page not knowing about what data to expect sounds really odd. Can't you just re-fetch the same data?

Upvotes: 2

Related Questions