Learn PHP From Scratch Day-6

PHP Control Structures: If else, Switch Case

Some times we needs to execute only part of code, but don’t want to delete other part of code cause it needs in different condition. Imagine you are creating user management system, where you need to give access to user if user is logged in else redirect it to the login page. So in such case you need Control Structure. There are 2 types of Control structures.

  • Sequential — this one involves executing all the codes in the order in which they have been written.
  • Decision — this one involves making a choice given a number of options. The code executed depends on the value of the condition.
  • Definition : A control structure is a block of code that decides the execution path of a program depending on the value of the set condition.

Lets See Example of IF..ELSE Statement in PHP code..


<?php$a = 90;$b = 21;if ($a > $b){echo "$a is greater than $b";}else{echo "$b is greater than $a";}?>


90 is greater than 21

PHP Switch Case

Switch… case is similar to the if then… else control structure.

It only executes a single block of code depending on the value of the condition.

If no condition has been met then the default block of code is executed.

It has the following basic syntax.

switch(condition){case value://block of code to be executedbreak;case value2://block of code to be executedbreak;default://default block codebreak;}


  • “switch(…){…}” is the control structure block code
  • “case value: case…” are the blocks of code to be executed depending on the value of the condition
  • “default:” is the block of code to be executed when no value matches with the condition

How it works

The flow chart shown below illustrates how the switch control structure works

Switch Cases

Practical example

The code below uses the switch control structure to display a message depending on the day of the week.

<?php$today = "Friday";switch($today){case "Sunday":echo "Have Fun Enjoy.";break;case "Friday":echo "Checkout , New Movie Released Today !";break;case "Saturday":echo "It's Half Day Today, Make Plan For Sunday.";break;default:echo "Have A nice Working Day";break;}?>


Checkout , New Movie Released Today !


  • Control structures are used to control the execution of the program
  • The if then… else is when you have more than route block of code to execute depending on the value of the condition
  • Switch… case is used to when you have a number of block codes, and you only have to execute one of them depending on the value of the set case.

Leave a Comment

Your email address will not be published. Required fields are marked *