Reputation: 91
I have a php file that validates a simple form entries for me. I assign each error ( found during the validation to a variable ($name_errors, $phone_errors and $email_errors). Each one of those variable contains a string ('Please enter a valid name', 'Please enter a valid phone number', and 'Please enter a valid email address'). I then create an array containing these variables called $errors. So the array will look like this
$errors = array($name_errors, $phone_errors, $email_errors);
Once I have the $errors array I run though an if statement as shown in the code below. Essentially, if errors were found, the statement is supposed to JSON_Encode the $errors array and exit the script. If no errors are found, the script will proceed to send the mail. The problem I have is that whether the array is empty (i.e., containing all null values as confirmed via var_dump()
) or containing actual errors values, it is always recognized by the if statement as containing data and will stop the script explained above.
if ($errors != null){
var_dump($errors);
echo json_encode( $errors );
exit;
};
And here is the results I get from var_dump(array) which the JSON encoding always consider it not equal to $errors=null:
Result: [null,null,null] contact_form.htm:323:13
Upvotes: 1
Views: 68
Reputation: 41810
Consider this alternate approach: use one variable, $errors = []
. As you validate your input, add any errors that occur under the appropriate key in that array, e.g.
if (!validate($name)) {
$errors['name'] = 'Please enter a valid name';
}
Then if there are no errors then the array will be empty, so conditionally printing it becomes a little simpler.
if ($errors) { // empty array evaluates as false, non-empty as true
echo json_encode($errors);
exit;
}
Collecting all of your errors in a single variable rather than using separate ones can be advantageous. One is that when you add another form field you won't have to remember to add its error variable to the array that collects all the different error variables.
Upvotes: 1
Reputation: 147146
An array full of null
values is not empty, nor is it equal to null
as you are testing. Consider this:
$errors = [null, null, null];
echo $errors == null ? "true\n" : "false\n";
echo empty($errors) ? "true\n" : "false\n";
Output:
false
false
Instead, you can test the output of array_filter($errors)
, which will be an empty array if all values in $errors
are null:
echo empty(array_filter($errors)) ? "true\n" : "false\n";
Output:
true
So try changing your code to:
if (!empty(array_filter($errors))) {
Demo on 3v4l.org
Manual for array_filter
Upvotes: 1