Be Deadly Effective at Using “if” Statements

Image for post
Image for post
A guide for beginners of any background to start writing codes

the previous article, we briefly touched on the subject of decision making. It is used for solving dilemmas and performing a set of tasks on a decision made in programming.

In this article, we are going to address two particular scenarios that are common when using “if” statements along with some tricks.

What if I don’t have a case for “else”?

It’s perfectly normal for an “if” statement to have no “else”. The reason is simple, we sometimes do not wish to perform some actions when the decision was ruled against a dilemma.

An example can be given from our famous chat room scenario. What if, instead of displaying a message to anyone who’s under 18 and simply just ignore them? Like an arrogant butler who only greets people who made it into the chat room.

In reality, it is logically viable and computers will let you define an “if” statement without an “else” clause. Consider the following example.

<?php    $counter=1;    while ($counter<=5)    {        if(18 <= readline('Hi, how old are you? ')){             echo 'Good morning master '.readline('What is your name: ');             $counter++;        }    }?>

In this case, the program will only greet those people whose ages are 18 and older. It will simply ignore whomever is under 18 and move onto asking the next person.

Code Explanation:

The definition of “else” is nowhere to be found due to the fact that our program, will do nothing when the condition of age being more than or equals to 18 is “false”.

Only when a guest is not an under age person, we perform the set of tasks of greeting the guest and update the guest count.

Whoa! that’s by far the shortest code explanation we’ve ever had!

That’s because you’ve already learned so much and fully understood them, so give yourself a pat on the back and smile.

What if I have multiple cases for “else”?

Let’s think of a wild case for our scenario of a chat room. By wild I mean, what if I want to have 4 different ways to greet our guest based on their ages? Like displaying a different message for people whose age is under 18 (Juvenile), between 18 and 34 (Young Adults), 35 to 64 (Adults), 65 and older (Seniors).

Interesting, there are two ways to achieve that and please stop if you are considering writing multiple “if…else…” statements. Believe me, one is enough, we just need to write it properly.

We can have no “else”, we can also have infinite “else”s

You heard it right, you can write one “if” statement and multiple “else”s with a slightly different keyword. Let’s take a look at the implementation of our scenario below.

<?php    $counter=1;    while ($counter<=5)    {         $age = readline('Hi, how old are you? ');         if($age < 18 ){            echo 'I cannot let you in since you are underage.';         }elseif($age < 35){            echo 'Hello master '.readline('What is your name: ');            $counter++;         }elseif($age < 65){            echo 'Your majesty, my master '.readline('What is your name: ');            $counter++;         }else{            echo 'It is an honor to meet you! Master '.readline('What is your name: ');            $counter++;         }    }?>

Code Explanation:

We store the age entered by the user into a variable again, because it is to be used on multiple occasions in the later program.

We start our “if” statement with the keyword “if” along with the condition to examine. In our case, we start by checking if the age is below 18 and the scope defined underneath the “if” keyword will be executed accordingly if the condition is “true”.

We use the keyword “elseif” to instruct the computer to only check the condition defined afterward when the previous condition is “not true”.

If the condition defined within an “elseif” is “true”, it executes what’s defined within the scope underneath the “elseif” keyword and forget about running for the rest of the “elseif”s.

Conversely, if the “elseif” condition is not met, it will move onto the next “elseif” if there were any.

We end the entire “if” statement with the old friend “else” to catch all conditions that were not met from the previous assumptions. Of course, you can omit this “else” if we simply do not care about the rest of the situations.

Cool stuff right? But there seems to be an issue, at least for me.

I don’t like to write “$counter++” and update the guest count within the scope of action for every condition. I’m sort of lazy and wishing to write “$counter++” only once.

The concept to achieve that is quite simple. We see that the only situation a guest count is not updated is when a guest is under age. So all we need to do is to separate the actions for these two groups of people.

With what? One might ask. With “if” statement I shall say.

Here’s how in codes.

<?php    $counter=1;    while ($counter<=5)    {        $age = readline('Hi, how old are you? ');        if($age < 18 ){             echo 'I cannot let you in since you are underage.';        }else{             If ( $age < 35){                  echo 'Hello master '.readline('What is your name: ');             }elseif( $age < 65 ){                  echo 'Your majesty, my master '.readline('What is your name: ');             }else{                  echo 'It is an honor to meet you! Master '.readline('What is your name: ');             }             $counter++;         }

Code Explanation:

First and most importantly, we need to notice that we created two sets of actions and separated them by one condition, that is when a guest is under age.

When a guest is under age, we do our normal stuff, but when a guest is not under age, we use an “if…else” along with a series of “elseif”s to decide which message to display. At the same time, we update the guest count when the message is displayed.

That’s right, who says we can’t put an “if” inside another “if” and create a nested “if” statements?

Now that looks clean to me, what do you think?

The jaw-dropping technique when using “if”s

Lastly, let me introduce you to a technique that not every language out there is using, but looks super cool when used. Sort of like a way to show people that, you know what you are doing when coding. You can certainly skip this section if you found this piece of information useless.

There is this thing called shorthand or ternary “if…else” statements, and it looks like the following.

(condition)?action when true : action when false ;

Please don’t panic! And let me explain.

To apply this technique on our early example of greeting our guests and refusing under age juvenile, we have our program looking like the following.

<?php     $counter=1;     while ($counter<=5)     {          echo (                   ( 18>readline('Hi, how old are you? ') ) ?                   'I cannot let you in since you are underage.' :                   echo 'Good morning master '.readline('What is your name: ') ;                )      }?>

Code Explanation:

I break the lines so that you can see where the operators(? : ;) are. In reality, everything after “echo” could be one line of code.

Everything starts with this “echo” instruction. It tells the computer to display something, and the contents to be displayed is being decided based on the later statements.

A condition to be examined for the dilemma is again put inside the brackets, but followed by a question mark (?). This very question mark instructs the computer to treat everything in front of it as an “if” statement.

Whatever defined after the question mark is executed as if the condition was “true”, but following by a colon (:). This colon marks the end of the scope of which, is being executed when the condition is true.

Everything after the colon (:) is executed only if the condition was “not true”. Exactly like whatever was defined inside a scope of an “else” statement.

Finally, the entire statement of everything jumbled is marked with a semicolon (;) to tell the computer the statement ends here.

It certainly is a convenient shorthand statement to use if you understand the concept behind it. I was only putting this out there so that it might just come in handy for you one day.

Don’t feel troubled if you didn’t get it. Some languages don’t even have this feature. This knowledge is here for fun.


  • “If” statements can be used with no “else” clause for situations which we don’t want to do anything when the condition is “not true”.
  • “If” statements can have multiple sub-conditions to be examined when the previous condition is “false”. We chain these examinations by keyword “elseif”.
  • Multiple “if” statements are not the same as a “if” statement with many “elseif”s.
  • We use “if…elseif…else” because we have multiple sets of actions designed to be performed by many dependent occasions.meaning the occurrence of one event is depending on the occurrence of another.
  • “If…else” statement can be converted into a shorthand/ternary statement. The format for a ternary “if…else” is “ (condition) ? action when true : action when false ; “.

That was a very long article so far we’ve had and I apologize for not being able to chop these into smaller versions. I really hate to create another article just to cover some additional features of “if” statements. I hope you won’t mind.

In the next article we are going to take a look at the last member of the decision making family, so please stay tuned.

Written by

Laravel Expert, AI enthusiasts. Recently fell in love with helping people rebuild their lives by learning how to program.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store