Check expected values from radio buttons and check boxes

I want to find the most efficient way of checking that all of a form’s radio button groups and individual check boxes have (if they have been selected) the values that were set in the HTML. For expediency, I’ve had to use an if statement that checks each in succession. It works, but I’m sure that there is a more resource-efficient way. I can only write a plain English description of what I envisage, which would be something like:

  • gather only the relevant keys/values from the inputs array
  • write an array of allowed values
  • compare the incoming values with the 2nd array

All of these inputs are optional, so they may be empty. I’ve looked at the arrays section of the PHP manual, Googled (don’t know what to search for, though), checked a few books, but got almost nowhere. I found out how to check the value of a single key, e.g. from a radio group, but I would prefer to be able to wrap it all in one simple function.

Hopefully this sort of illustrates what you’re looking for.


<?php
   $water_bottles = array ('Arrowhead','Dasani','Nestle');


    if ($_POST['submit'] == 'water_survey') {
		foreach ($_POST['water_bottle'] as $v)
		{
			if (in_array($v, $water_bottles)) {
				# anything in here was submitted by the user and a valid value
			}
		}

	}
?>
	
<form method='post' action='form.php'>
	<?php
		foreach ($water_bottles as $v)
		{
			echo "<input type='radio' value='$v' name='water_bottle[]' /> $v<br/>";
		}
	?>
	<input type='hidden' name='submit' value='water_survey' />
	<input type='submit' value='Submit' />
</form>

Thanks for responding. But unless I’ve misinterpreted your code, that’s checking just one post value, yes? From one radio button group. As I mentioned, I found out how to check each group, or an individual check box, but I have quite a few to check so being able to do them in one function would be a boon.

One quick question for you, though: do the square brackets in your example’s input name do anything?