testing for checkboxes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Skittlewidth
Forum Contributor
Posts: 389
Joined: Wed Nov 06, 2002 9:18 am
Location: Kent, UK

testing for checkboxes

Post by Skittlewidth »

What would be the most efficient way of checking 27 checkboxes to see if they are set (given that they pass no value at all if left blank).

I don't want to type if (isset()){....} 27 times. Currently they have meaningful names. Should I rename them all to have a prefix and unique numbers and loop through them, and get confused about their function later when I revisit the code, or is there another way?

My brain has already left for its christmas vacation by the looks of things... :roll:
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

Code: Select all

<form method="post">
<input type="checkbox" name="checkboxgroup[]" value="1">
<input type="checkbox" name="checkboxgroup[]" value="2">
<input type="checkbox" name="checkboxgroup[]" value="3">
<input type="checkbox" name="checkboxgroup[]" value="4">
<input type="checkbox" name="checkboxgroup[]" value="5">
<input type="submit">
</form>

Code: Select all

if (is_array($_POST['checkboxgroup'])) {
  echo "The following boxes were set: ".implode(",",$_POST['checkboxgroup']);
}
That's the easy way .. however .. I don't agree with this line: "I don't want to type if (isset()){....} 27 times" .. it's just lazy. You're trying to avoid a bit of typing, and you're sacrifising the integrity, maintainability, readability, and security of your code in the process. Checkboxes should be grouped logically. If there are 27 seperate things to tick then you should have 27 seperate isset() functions.
User avatar
Skittlewidth
Forum Contributor
Posts: 389
Joined: Wed Nov 06, 2002 9:18 am
Location: Kent, UK

Post by Skittlewidth »

8O


I told you my brain had left me.

Quite frankly, I'm embarrassed! I always usually use arrays for groups of checkboxes... what an idiot!

More sherry anyone? *Hic* :oops:

Edit: Onion2k, I agree with you about the way checkboxes are grouped though. There is a school of thought that says you shouldn't ever use the value attribute with a checkbox, and that the name is the checked value. (Hence me giving meaningful names). In this case 20 of the checkboxes do relate to a specific subject, so I could get away with the array method. But I wouldn't use this method to check an entire page of checkboxes if they weren't related.

Sorry if it sounded lazy about the if (isset()) thing. I was actually concerned about how the code would look on the page for editting later. I was trying to keep things neat.
Post Reply