php – 数组和foreach

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 数组和foreach脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
知道为什么不打印这些错误吗?

// 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未设置的通知.

脚本宝典总结

以上是脚本宝典为你收集整理的php – 数组和foreach全部内容,希望文章能够帮你解决php – 数组和foreach所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。