PHP Decision Making

PHP Decision Making Statements

PHP decision statements are used to make a decision, based on some conditions.


Type of Decision-Making Statements:

Here are different types of Decision Making Statements in PHP.

  • The if…else statement
  • The elseif statement
  • The switch…case statement

The if….else statement

The if statement is used to execute a block of code only if the specified condition is true.

Syntax

if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

<?php
$day = "Friday";
         
         if ($day == "Friday") {
            echo "its Friday"; 
         } else {
         echo "its not Friday";
} 
?>

Try & Run Here : http://ideone.com/ajJf81

Tutorials Class - Output Window

its Friday


The elseif Statements

If you want to execute some code if one of the several conditions are true use the elseif statement.

Syntax

if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

<?php
         $day = "Sunday";
         
         if ($day == "Friday") {
            echo "its friday";
         }
         else if ($day == "Sunday") {
            echo "its weekend";
         } else {
            echo "its not weekend as well not Friday"; 
         }
?>

Run : http://ideone.com/kA3Xdu

Tutorials Class - Output Window

its weekend


The switch…case statement

The switch statement is used to perform different actions based on different conditions.

Syntax

switch(n){
case label1:
// Code to be executed if n=label1
break;
case label2:
// Code to be executed if n=label2
break;
...
default:
// Code to be executed if n is different from all labels
}

<?php
$fav_fruit = "mango";
 
switch ($fav_fruit) {
    case "orange":
        echo "Your favorite fruit is orange!";
        break;
    case "mango":
        echo "Your favorite fruit is mango!";
        break;
    case "apple":
        echo "Your favorite fruit is apple!";
        break;
    default:
        echo "Your favorite fruit is neither orange, mango, nor apple!";
}
?>

Run : http://ideone.com/Muu9Go

Tutorials Class - Output Window

Your favorite fruit is mango!


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a program to check student grade based on marks
Write a program to show day of the week using switch
Write a program to calculate Electricity bill in PHP
Write a simple calculator program in PHP using switch case
Write a PHP program to check if a person is eligible to vote
Write a PHP program to check whether a number is positive, negative or zero
Interview Questions & Answers
No Content Found.