HTML and CSS Reference
In-Depth Information
print out the <input> tags, using toys[] as the parameter name to let PHP know that this
field can have multiple values and should be treated as an array. To include the value for
a field, I just use a short tag to insert the key into the value attribute of the tag. I use it
again to print out the label for the check box, $value , after the tag. The last bit here is
the if statement found within the <input> tag. Remember that if you want a check box
to be prechecked when a form is presented, you have to include the checked attribute. I
use the in_array() function to check if the key currently being processed is in
$_POST['toys'] . If it is, I then print out the checked attribute using echo() . This
ensures that all the items the user checked before submitting the form are still checked if
validation fails.
A browser displaying a form that contains some errors appears in Figure 21.2. Here's the
full source listing for the page:
$toys = array('digicam' => 'Digital Camera',
'mp3' => 'MP3 Player', 'wlan' => 'Wireless LAN');
$errors = array();
$errors = validate();
function validate() {
$errors = array();
if (empty($_POST['name'])) {
$errors['name'] = 'You must enter your name.';
if (!is_numeric($_POST['age'])) {
$errors['age'] = “You must enter a valid age.”;
if (empty($_POST['toys'])) {
$errors['toys'] = 'You must choose at least one toy.';
return $errors;
<!DOCTYPE html>
Search WWH ::

Custom Search