I thought I knew how to use arrays until I started storing form filling errors in them. So here is the situation: I want to declare an array at the beginning of my PHP document. Then throughout the document there is validation and at each validation the array is filled with an error if an error should be produced. Then at the end of the document I want to echo these errors into a specific on the page. So here is what I have now:
$errors = array();//declares array
if(/*some qualifier*/) {//username validation
} else {
$errors[] = "<p>Please enter a valid username</p>";
}
if(/*some qualifier*/) {//email validation
} else {
$errors[] = "<p>Please enter a valid email</p>";
}
echo '<div id="errors">';//errors div
foreach ($errors as $value) {//fills error div with the errors LINE 60
echo "$value<br />\n";
}
echo '</div>';
So… what is wrong with that? I keep getting an error that errors is an undefined variable when it tries to echo the errors.
The error as given in the comments:
An error occurred in script ‘file path’ on line 160: Undefined variable: errors
Update: seems like its a problem with something weird in my code. If you feel like looking through 217 lines of code here is all the code: http://pastebin.com/YkERYpeF
I have seen your code. You did only declare $errors inside a condition:
PHP arrays work great. You are declaring variables in a conditional scope and using them in a global scope. And PHP can’t imagine you want to use that variable in the global scope.
You ought to indent your code as well, but you can perfectly define
$errorsjust below$bodyIdand PHP won’t complain anymore.