Learn PHP from Scratch Day -6

Learn PHP from Scratch Day -6
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.

if else statement

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

numbers.

Output:

90 is greater than 21

PHP Switch Case

Switch… caseis similar to the if then… else control structure.

It only executesa 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.

HERE,

  • "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.

Output:

Checkout , New Movie Released Today !

Summary

  • 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.