1

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.

3 Answers 3

2

I just have to correct the argument of the 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. When it isn't 0, the content of the else is executed and the errors are printed. It's just the opposite of what you did. (I also corrected the sentence: it's ‘there are errors’, not ‘there is errors’ :P)

Furthermore, the other if is wrong as well, it should be the opposite:

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

since you need to check when the password is less than 6 characters.

Sign up to request clarification or add additional context in comments.

1 Comment

Further, you don't even need the count($errors), as an empty array will evaluate to FALSE. You can do if($errors) { echo 'there are errors'; }
1

Shouldn't it be:

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

?

BTW you should use at least constants instead of magic numbers, e.g.

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.

Comments

0

Your if statement is messed up. 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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.