HTML and CSS Reference
In-Depth Information
there's an error associated with this field. To do so, I use the
array_key_exists()
func-
tion, which is yet another built-in PHP function. Remember that the keys in
$errors
are
the names of the fields with errors. So if the
$errors
array contains an element with the
key
name
, it means that this field was not valid.
If there is an error with the field, I include the attribute
class=”error”
in the
<label>
tag for the field. When the form is presented, the label will be red, indicating to the user
that she needs to fix that field, even if the user didn't bother to read the list of errors. If
there isn't an error, the normal
<label>
tag is printed.
When that's done, I just have to print out the
name
field, but in this case I need to include
the value that was submitted for the field if it's available. I include the
value
attribute in
my
<input>
tag, and I use a short tag to include the value of
$_POST['name']
as the
value. Inside the expression evaluator, I've wrapped the variable containing the value for
the field in the
strip_tags()
function. This PHP function automatically removes any
HTML tags from a string, and it's used here to thwart any possible cross-site scripting
attacks a malicious person might employ.
The
age
field is identical to the
name
field in every way except its name, so I skip that
and turn instead to the
toys
field. Here's the code:
<p>
<?php if (array_key_exists('toys', $errors)) { ?>
<label for=”toys[]” class=”error”><b>
Toys:
</b></label>
<?php } else { ?>
<label for=”toys[]”><b>
Toys:
</b></label>
<?php } ?>
<br />
<?php foreach ($toys as $key => $value) { ?>
<label><input type=”checkbox” name=”toys[]”
<?php if (in_array($key, $_POST['toys'])) { echo 'checked=”checked” '; } ?>
value=”<?= $key ?>” />
<?= $value?>
</label><br />
<?php } ?>
</p>
As you can see, the code for marking the label for the field as an error is the same for
this field as it was for
name
. The more interesting section of the code here is the loop that
creates the check boxes. When I was describing the form-processing section of the page,
I explained that I put all the toys inside the array
$toys
so that I could print out the
check boxes using a loop. There's the loop.
The values in the
<input>
tags are the keys in the array, and the labels for the check
boxes are the values. I use the associative array version of the
foreach
loop to copy each
of the key/value pairs in the array into the variables
$key
and
$value
. Inside the loop, I