简体   繁体   English

PHP数组无法正确输出

[英]PHP array not outputting properly

I am trying to do form validation but when I try to print out the contents of an array when there is an error it doesnt output anything. 我正在尝试进行表单验证,但是当我尝试在出现错误时打印出数组的内容时,它不会输出任何内容。

$errors = array();

if (strlen($password) >= 6) {
    array_push($errors, "Your password is not long enough! Must be over 6 characters!");
}

if(count($errors) !== 0) { 
...
} else {
    echo "There is errors<br/>"; 
    foreach($errors as $er){
        echo $er . "<br/>";
    }
} 

What I do get is "There is errors" so I know that the if else is working. 我得到的是“有错误”,因此我知道if可以正常工作。

I just have to correct the argument of the if : 我只需要更正if的参数:

if(count($errors) === 0) {
     // everything is okay
} else {
    echo "There are errors<br/>"; 
    foreach($errors as $er){
        echo $er . "<br/>";
    }
}

In this way, when your error count is 0, the content of the if is executed. 这样,当错误计数 0时,将执行if的内容。 When it isn't 0, the content of the else is executed and the errors are printed. 不为0时,执行else的内容并打印错误。 It's just the opposite of what you did. 这与您所做的相反。 (I also corrected the sentence: it's 'there are errors', not 'there is errors' :P) (我也纠正了这句话:它是“有错误”,而不是“有错误”:P)

Furthermore, the other if is wrong as well, it should be the opposite: 此外,另一个if也是错误的,也应该相反:

if (strlen($password) <= 6) {

since you need to check when the password is less than 6 characters. 因为您需要检查密码少于 6个字符的时间。

Shouldn't it be: 不应该是:

if (strlen($password) < 6) {
  array_push($errors, ...);

?

BTW you should use at least constants instead of magic numbers , eg 顺便说一句,您应该至少使用常量而不是幻数 ,例如

define('MIN_PASSWORD_LENGTH', 6);

// ...

if (strlen($password) < MIN_PASSWORD_LENGTH) {
    array_push($errors, "Your password is not long enough!"
      . " Must be over ".MIN_PASSWORD_LENGTH." characters!");
}

This way, if your minimal required length changes, you just have to change it once. 这样,如果最小所需长度发生变化,则只需更改一次即可。

Your if statement is messed up. 您的if语句搞砸了。 You are checking for errors, then doing nothing, then the else is where it is displaying the errors. 您正在检查错误,然后什么也不做,然后在其他地方显示错误。 Try this: 尝试这个:

if(count($errors) >0) {  //there are errors 
    echo "There is errors<br/>"; 
    foreach($errors as $er){
        echo $er . "<br/>";
    }
}else{
    //there are no errors
}

Also, your password length should be <=6 not greater than or equal to if it is too short. 另外,如果密码长度太短,则密码长度应小于等于<=6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM