Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Robert Walker
Robert Walker
17,146 Points

Refactoring if else if

I have a signup form that needs a lot of checks to see if fields are empty and have ended up with a rather long part of code that just looks wrong.

 if (empty($username)){
      $Err = "Please enter a username!";

   } else if (empty($password)){
      $Err = "Please enter a password!";

   } else if (empty($email)){
      $Err = "Please enter your email address!";

   } else if (empty($dob)){
      $Err = "Please enter your date of birth!";

   } else if (empty($empid)){
      $Err = "Please enter your empid!";

   } else if (empty($gforl)){
      $Err = "Please enter your gforl!";

   } else if (empty($firstName)){
      $Err = "Please enter your first name!";

   } else if (empty($lastName)){
      $Err = "Please enter your last!";

   } else if (empty($address)){
      $Err = "Please enter your address!";

   } else if (empty($postCode)){
      $Err = "Please enter your zip / post code!";

   } else if (empty($gender)){
      $Err = "Please select your gender!";

   } else if (empty($country)){
      $Err = "Please select your country!";

   }

I know I could add all this to an array: name-value-errorMessage and loop over but is there better ways of doing this as I assume its a common thing with signup forms.

1 Answer

you could loop over the POST variable itself which i believe key => value set so you dont have to create any arrays yourself..

foreach ($_POST as k=>v){ if empty(v){ error[] = k } }

// echo out error after checking if it has something in it

Robert Walker
Robert Walker
17,146 Points

The problem is that each error is personalised, select, enter, a, zip / post code etc. I don't really want to have a generic error message.

After looking around for a while it seems the best way to add this would be an array with the error messages too.

Thank you for the reply though.