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 />
";
}
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:
//if the user has registered
if (isset($_POST['submitted'])) {
require_once (MYSQL); //gets the database connection
$errors = array(); // declares the errors array that will be printed at end of validation if needed
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 $errors
just below $bodyId
and PHP won't complain anymore.
Chances are something in one of your validation blocks is using $errors for its own purposes, some function called somewhere in there uses global $errors
, or something is screwing it up in some other manner.
I've found the quickest way to track down this sort of thing is to insert a check on the variable somewhere in the middle and basically do a binary search on the code until you track down just where the variable is being reset.