arrays and foreach
Any idea why this wont print the errors?
// Validate the email
if (preg_match($regex, $email))
$errors[] = "Invalid email address";
// ... and the password
if (strlen($password) < 4)
$errors[] = "Password is too short";
// No errors?
if (emp开发者_开发技巧ty($errors))
{
// insert into db
}
// If there were any errors, show them
if (!empty($errors))
{
$errors = array();
foreach ($errors as $error)
echo '<li>'.$error.'</li>';
}
you are overwriting the array before output.
$errors = array(); // Creates an empty array
foreach ($errors as $error) // Won't do anything
remove $errors = array()
and it should work.
It would be cleaner by the way to initialize $errors = array()
in the very beginning of the script, and then check for count($errors) > 0
instead of empty
:
// No errors?
if (count($errors) == 0)
{
// insert into db
}
// If there were any errors, show them
else
{
$errors = array();
foreach ($errors as $error)
echo '<li>'.$error.'</li>';
}
that way, you will avoid notices about $error
not being set.
...because you're emptying the array just before trying to display its contents, see below
// If there were any errors, show them
if (!empty($errors))
{
$errors = array(); // This line is emptying the array!
foreach ($errors as $error)
echo '<li>'.$error.'</li>';
}
Because this line wipes the array:
$errors = array();
You are using this portion of code :
if (!empty($errors))
{
$errors = array(); // Here, you are making the $errors array empty !
foreach ($errors as $error)
echo '<li>'.$error.'</li>';
}
Basically : you are emptying the array before trying to iterate over it with foreach
-- so foreach
will not loop at all, as you are giving it an empty array.
Because you're overwriting the value of $errors
in the first line if the last if
statement.
精彩评论