Radio button validation in PHP using array_key_exists

<?php
$animals = array('dog' => 'D',
                 'cat' => 'C',
                 'bird' => 'B');
foreach ($animals as $key => $animal) {
   echo "<input type='radio' name='animal' value='$key'/> $animal \n";
}
 
if (!array_key_exists($_POST['animal'], $animals)) {
    echo "You must select a valid animal.";
}
?>

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.