Checking to see if a checkbox is checked

Say I have an input selction like this:
<input type=“checkbox” name=“Sam” /><br />
<input type=“checkbox” name="John’ />

Then I want to check to see which was selected in PHP. Something with IF/ELSE statements I think.

If you have those inputs as they are and you select both, the $_POST will contain:


Sam = on
John = on

If you only check John, it will not contain Sam.

If you want the user to be able to select Sam and John, I would change your form slightly:


<form method="post">
	<label for="sam">Sam: <input type="checkbox" name="Sam" id="sam" value="1" /></label><br />
	<label for="john">John: <input type="checkbox" name="John" id="john" value="1" /></label><br />
	<input name="submit" type="submit" value="submit" />
</form>

Try this in PHP:


if(isset($_POST['Sam']) && isset($_POST['John'])) {
	echo 'you selected both Sam and John';
} else if(isset($_POST['Sam'])) {
	echo 'you selected Sam';
} else if(isset($_POST['John'])) {
	echo 'you selected John';
} else {
	echo 'you did not select anyone';
}

If you want the user to select Sam or John, the way I would do it is to have a radio with name as “name” and set the value to Sam or John, like so:


<input type="radio" name="firstname" value="Sam" />
<input type="radio" name="firstname" value="John" />

Then with PHP, you will only get one value “$_POST[‘firstname’]”.

Cheers;
Poncho

Couldyou do this with an array of check boxes?