• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

[PHP] How to not work with if-statements

divegia

New Member
Joined
Dec 13, 2016
Messages
21
Reaction score
4
Hi there!

This "tutorial" is meant for users with some experience of PHP. It's not a guide for complete beginners.

I have been going through most AAC systems out there and found many nested if statements. They drive me nuts every time I see them.

Here is an example how nested if statements use to look: (bad)
Code:
if(isset($_POST['username']) && isset($_POST['password'])){
    if(strlen($_POST['username']) >= 6 && strlen($_POST['username']) <= 20 ){
        if(username_is_valid($_POST['username'])){
            if(!username_exists($_POST['username'])){
                // we create the user now!
                create_user($_POST['username'],$_POST['password']);

               // redirect, send email and so on here....
            }else{
               die("This username already exists.");
            }
        }else{
                die("Your username is not valid.");
        }
    }else{
         die("Your username must be at least 6 character long and maximum 20 characters.");
    }
}else{
   die("Missing fields!");
}
Looking at this example, I haven't even validated password, email and so many more variables that may be used. This code is very messy, it is hard to follow up and see what is happening. Imagine 5 - 6 more if statements in this code.

Here is an example of how the same thing should be solved, in a better and cleaner way:

Code:
if(!isset($_POST['username']) || !isset($_POST['password']))
{
   die("Missing fields");
}

$username =  $_POST['username'];
$password = $_POST['password'];

if(strlen($username) < 6 || strlen($username) > 20)
{
   die("Your username must be at least 6 character long and maximum 20 characters.");
}

if(!username_is_valid($username))
{
   die("Your username is not valid.");
}

if(username_exists($username))
{
   die("This username already exists.");
}

// everything ok! let's create the username now
create_user($username,$password);

// send email, redirect with success message and so on here..
This last example is much cleaner and easier to follow up what is happening. This is just an example, of course there are situations you will need to create nested if statements, but it should be limited and under control so the code is cleaner. Now, many MVC based frameworks might help one to that direction. But mostly it's about creating good habits when you code.

Of course, using the function die() and the global $_POST variable was just for demonstration.

Hope you like it!
 
Last edited:
Back
Top