Lesson 7 – Decision Making in PHP

Sometimes, you have to take decisions depending upon the conditions you have to meet. We use if, else…if and if else…if else statements to make these decisions. Let us explain all of them one by one.

The If Statement

The “if statement” checks whether or not a condition is true. If it is true, it will execute the code in the curly brackets. Have a look at its syntax.

<?php
if (condition) {
  Execute the code if condition is true;
}

?>

Here is an example of If statement.

<?php 
if (7 < 10) {
echo "The statement is true";
}
?>

As 7 is indeed less than 10, the code will be executed as shown in the following figure. However, Apache will do nothing if the statement is wrong.

The If…Else Statement

The if…else statement provides you with more control when it comes to decision making in PHP. It offers you a sort of backup if a condition is untrue. You can add another condition and force apache to test it as well. If the second condition is true, Apache will execute the code. Here is the syntax of if…else statement.

<?php 
if (condition)
Execute the code if the condition is true;
else
Execute the code if the condition is false;
?>

The following is an example of if…else statement.

if (7 > 10)
   echo "The statement is true"; 

else
   echo "The statement is false"; 
?>

As 7 is not greater than 10, the first statement is false. Therefore, Apache will print the second option available to it that is “The statement is false.”

The If…Else If Statement

if.. else if statement enables PHP to consider more than 2 conditions before making a decision. The following is the syntax of this particular type of statement.

<?php 

if (condition 1 ) {
    Execute the code if the condition is true
 } else if (condition 2) {
    Execute the code if the condition is true
 } else if (condition 3) {
    Execute the code if the condition is true
 } else {
     Execute this code if no condition is true
 }

 ?>

Here is an example of if…else if statement.

<?php 

if (7 > 10) {
 echo "7 is greater than 10";
} else if (8 > 10) {
 echo "8 is greater than 10";
} else if (5 < 10 ) {
 echo "5 is less than 10";
} else {
 echo "No condition is true";
}
?>

As 5 is less than 10, Apache will execute the third condition.

In the next lesson, we will throw some light on Switch Statements