I have a sign up form with about 10 fields and they are all required to be filled in before processing, so trying to avoid all those if checks I came up with this, is this a good method?
foreach($list as $items) {
if(empty($items)) {
$error[] = "All fields are required.";
break;
}
}
or should I make if(empty($field_1) || empty($field_2) etc.. then output the error?
Assuming that your data is coming from
$_GETor$_POST, all data fields will be strings. This means that you should be able to do the check in a single function call:This looks for strings which are exactly equal to an empty string. If you want to make the comparisons loose (more or less identical to the check that
empty()does) just remove the finalTRUE.EDIT Thinking about it, you don’t need the strict comparison. I did this to allow for a legitimate field value of
'0'(whichempty()would not allow) but this will also be permitted with loose comparisons, since'0' != ''.ANOTHER EDIT If you want to check that the length of the sting is greater than two, you will have to loop:
This will also “clear out
0” assuming that by this you mean “not allow a value to be0“. If you also want to disallow'00'(or any other string that results in0) you can change theifclause to this: