PHP 8 - Conditional

Last modified: April 02, 2022

When we write a program, we need to perform different actions based on conditons. You maty be following conditional statement

  • if statement - executes if a condition is true
  • if...else statement - executes if a condition is true and another code one is false
  • if...elseif...else allows multiple conditions
  • selects one of many blocks of code to be executed

if...else...elseif Statements

<?php $age = 65; if ($age < 65) { echo "young"; } else { echo "elderly"; } ?>


<?php $age = 30; if ($age > 35) { echo "young"; } else if ($age > 50) { echo "old"; } else { echo "elderly"; } ?>


switch Statements

switch is more tidy if you have few more statements to be executed for a condition

<?php $day = "sunday"; switch ($day) { case "sunday": echo "Today is Sunday"; break; case "monday": echo "Today is Monday"; break; default: //if no case equals to any condition, then PHP go to default echo "No Day"; } ?>