LERAN PHP COMPLETE

Learn one of the most powerful programming languages in the world and become a rockstar developer.

PHP Decision Making


PHP Conditional Statements

Very often when you write code, you want to perform different actions for different conditions. You can use conditional statements in your code to do this.

In PHP we have the following conditional statements:

  • if statement - executes some code if one condition is true
  • if...else statement - executes some code if a condition is true and another code if that condition is false
  • if...elseif...else statement - executes different codes for more than two conditions
  • switch statement - selects one of many blocks of code to be executed

The ElseIf Statement

The if...else statement executes some code if a condition is true and another code if that condition is false.

if (condition)
    code to be executed if condition is true;
else
    code to be executed if condition is false;
<!DOCTYPE html>
<html>
<body>

<?php
$d = date("D");

if ($d == "Fri")
echo "Have a nice weekend!";

else
echo "Have a nice day!";
?>

</body>
</html>

The ElseIf Statement

The if...elseif...else statement executes different codes for more than two conditions.

if (condition)
    code to be executed if condition is true;
else if(condition)
    code to be executed if condition is true;
else
    code to be executed if condition is false;
<!DOCTYPE html>
<html>
<body>

<?php
$d = date("D");

if ($d == "Fri")
echo "Have a nice weekend!";

elseif ($d == "Sun")
echo "Have a nice Sunday!";

else
echo "Have a nice day!";
?>

</body>
</html>

The PHP switch Statement

Use the switch statement to select one of many blocks of code to be executed.

switch (expression){
    case label1:
      code to be executed if expression = label1;
      break;

    case label2:
      code to be executed if expression = label2;
      break;
      default:

    code to be executed
      if expression is different
      from both label1 and label2;
}
<!DOCTYPE html>
<html>
<body>

<?php

$d = date("D");

switch ($d){
      case "Mon":
      echo "Today is Monday";
       break;

case "Tue":
       echo "Today is Tuesday";
       break;

case "Wed":
       echo "Today is Wednesday";
       break;

case "Thu":
      echo "Today is Thursday";
      break;

case "Fri":
      echo "Today is Friday";
      break;

case "Sat":
      echo "Today is Saturday";
      break;

case "Sun":
      echo "Today is Sunday";
      break;

default:
      echo "Wonder which day is this ?";
}
?>

</body>
</html>

x
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Privacy Policy That's Fine