4

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?

Grigor
  • 4,139
  • 10
  • 41
  • 79
  • You should note that `empty` also returns true for `'0'` (a string that only contains the character 0). – Arjan Jan 29 '12 at 23:00

4 Answers4

3

it's ok. If you just want to show message "All fields are required." without showing which field in blank.

Otherwise it will be more user friendly if you check and show which field is left empty.

3

Assuming that your data is coming from $_GET or $_POST, all data fields will be strings. This means that you should be able to do the check in a single function call:

if (in_array('', $list, TRUE)) {
  $error[] = "All fields are required.";
}

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 final TRUE.

EDIT Thinking about it, you don't need the strict comparison. I did this to allow for a legitimate field value of '0' (which empty() 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:

foreach ($list as $item) {
  if (strlen($item) < 2) {
    $error[] = "All fields are required.";
    break;
  }
}

This will also "clear out 0" assuming that by this you mean "not allow a value to be 0". If you also want to disallow '00' (or any other string that results in 0) you can change the if clause to this:

if (strlen($item) < 2 || (!(int) $item)) {
DaveRandom
  • 87,921
  • 11
  • 154
  • 174
3

It's good idea to put it into loop as you did but please note that this will fail even when user inputs 0 and will pass for string containing only spaces, so you may want to make better checks than empty()

dev-null-dweller
  • 29,274
  • 3
  • 65
  • 85
2

I would approach this with an in_array check.

<?php
$fields=array('name','age','yadayada','something_else');

foreach ($_POST as $key=>$value){
    if(in_array($key,$fields) && $value!=''){
        $$key=$value;
    }else{
        $error[$key]='This field is required.';
    }
}
?>
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106