Decision Making or Conditional Statements in PHP

This article is created to cover decision making or conditional statements used in PHP, that are:

PHP Decision Making Statements Example

Here is an example demonstrating how decision making statements are used in PHP to control the program.

<?php
   $x = 10;
   $y = 20;
   
   if($x<$y)
      echo "The value of \$x is less than \$y";
?>

The output produced by above PHP example on decision making statement, is:

php decision making

Since the value of $x is 10, and the value of $y is 20. Therefore the condition $x<$y or 10<20 evaluates to be true. Therefore program flow executes the statement available in the body of if.

Let me create another example, that executes some other block of code, in case if the specified condition evaluates to be false:

<?php
   $x = 8;
   $y = 5;
   
   if($x<$y)
      echo "The value of \$x is less than \$y";
   else
      echo "The value of \$x is greater than \$y";
?>

The output should be:

The value of $x is greater than $y

Let me create one last example:

<?php
   $x = 8;
   $y = 8;
   
   if($x<$y)
      echo "The value of \$x is less than \$y";
   elseif($x>$y)
      echo "The value of \$x is greater than \$y";
   else
      echo "The value of \$x is equal to \$y";
?>

The output should be:

The value of $x is equal to $y

Note - The detailed description about switch along with these if...elseif...else are covered in its separate tutorial.

PHP Online Test


« Previous Tutorial Next Tutorial »