PHP - Creating a checkbox with limited choices

December 2016


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.

Related :

This document entitled « PHP - Creating a checkbox with limited choices » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.