Validating a drop-down menu with array_key_exists()
<?php
$choices = array('eggs' => 'E',
'toast' => 'T',
'coffee' => 'C');
echo "<select name='food'>\n";
foreach ($choices as $key => $choice) {
echo "<option value='$key'>$choice</option>\n";
}
echo "</select>";
if (! array_key_exists($_POST['food'], $choices)) {
echo "You must select a valid choice.";
}
?>
Related examples in the same category