php – 数组和foreach
发布时间:2020-12-13 22:00:23 所属栏目:PHP教程 来源:网络整理
导读:知道为什么不打印这些错误吗? // Validate the emailif (preg_match($regex,$email)) $errors[] = "Invalid email address"; // ... and the password if (strlen($password) 4) $errors[] = "Password is too short"; // No errors? if (empty($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 (empty($errors))
{
// insert into db
}
// If there were any errors,show them
if (!empty($errors))
{
$errors = array();
foreach ($errors as $error)
echo '<li>'.$error.'</li>';
}
解决方法
你在输出之前覆盖了数组.
$errors = array(); // Creates an empty array foreach ($errors as $error) // Won't do anything 删除$errors = array(),它应该工作. 通过在脚本的最开始初始化$errors = array()然后检查count($errors)>的方式会更清晰. 0而不是空: // 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>';
}
这样,您将避免关于$error未设置的通知. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
