PHP - Creating a checkbox with limited choices

October 2017


I am currently creating a PHP form in which there are check boxes.
  • I want to know how to limit the number of response options. For example, if the user checks more than one box, an error message is displayed.


Here's how it look:

<p>Choice</p>
<p>1 <input type="checkbox" name="reponse[]" value="1">
2 <input type="checkbox" name="reponse[]" value="2">
3 <input type="checkbox" name="reponse[]" value="3"></p>

<input type="submit" value="validate" name="ok"><br/>

<?php
	if (isset($_POST['ok']))
	{
                //empty message variable
		$msg = '';
		
		if(isset($_POST['reponse']))
		{
			echo '<p>Your choice : </p>';
			foreach ($_POST['reponse'] as $choix)
			{
				echo $choix.'<br/>';
			}
		}
		else
		{
		 echo 'Please make a choice';
		}
	}
?>

Solution


<html>
<body>
<p>Choice</p>
<p>
<form method="POST" action="index.php">
1 <input type="checkbox" name="reponse[]" value="1">
2 <input type="checkbox" name="reponse[]" value="2">
3 <input type="checkbox" name="reponse[]" value="3"></p>

<input type="submit" value="validate" name="ok"><br/>
</form>

<?php

	if (isset($_POST['ok']))
	{
                //empty message variable
		$msg = '';
		
echo ("the number is ".count($_POST['reponse']));
		
		if(isset($_POST['reponse']))
		{
			echo '<p>Your choice : </p>';
			foreach ($_POST['reponse'] as $choix)
			{
				echo $choix.'<br/>';
			}
		}
		else
		{
		 echo 'Please make a choice';
		}
	}
?>
</body>
</html>


Thanks to holow1 for this tip.
Published by aakai1056. Latest update on August 17, 2011 at 09:34 AM by aakai1056.
This document, titled "PHP - Creating a checkbox with limited choices," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (ccm.net).