Reputation: 1452
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.
Upvotes: 1
Views: 86
Reputation: 23011
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.
Upvotes: 1
Reputation: 6239
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.
Upvotes: 2
Reputation: 12059
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.
Upvotes: 0