21 – PHP if/else Statement


In my previous lesson, I have tackled the if statement which is important in PHP when used properly and it executes some code if one condition is true.


This time, let’s tackle about the PHP if/else statement, obviously as its name suggests, it is a combination of if and else. However, The if/else statement performs some code if a condition is equal or true and another code will be executed if that condition is false.




Here’s a simple example of an if/else conditional statement that is common in every day life. This is to make you more familiar with it, picture the following:

“If you study hard, then you will get a passing grade”. So, what happens, if you don’t study hard? Well, you fail!


  • If you study hard then you will get a passing grade.
  • Else, if you don’t study hard, then you will fail.


Here’s an example of the basic form of PHP if/else statement:



The if statement performed to true.



perform else code with false

If the if statement was false, then the code within the else segment would not be performed. Always keep in mind that the code contained in the if and else cannot be both performed, because the if statement cannot assess to both true and false at once. Below is the result of what would happen if we changed to $number_four to anything apart from number 4.




The if statement performed to false

You will see that the variable was set to 3, which is not equal to 4 and the if statement was false. Notice that the code segment within the else was used in the given example above.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.