PHP Control Structures

In PHP, control statements are divided in two categories:

  • Conditional Structure
  • Looping Structure

We will here discuss the conditional structure. We will cover the looping structure in the next tutorial

Conditional Structure:

  • Conditional Structure will test the condition or expression & based on the result it will allow us to control the execution of the different parts of the code at runtime.
  • Conditional Structure in PHP are classified as:-
    • if….else
    • Switch Case

If Else Statement:-

  • In if…else statement, firstly condition is checked.
  • If the condition is true, it will execute the true block code statement and then execute the final statement if mentioned. If the condition is false, it will execute the false block code statement and then execute the final statement.

Syntax:-

<?php
	if(condition){
			true block code statement;
	}
	else{
			false block code statement;
	}
?>

Flowchart:-

Flowchart If Else

Example:-

<?php
	$number = 10;
	if($number % 2 == 0){
		echo "Number is even";
	}
	else{
		echo "Number is odd";
	}
?>

Output:-

Number is even

Switch Case Statement:-

Switch case is used to choose one of the block codes from the number of block codes. It is useful when there are a list of choices and from which we have to select any one option at a time.

Syntax:-

<?php
	switch(condition){
		case value1:
		block code1;
		break;

		case value2:
		block code2;
		break; 

		case valueN;
		block codeN;
		break;
		
		default:
		default block code; 
	}
?>
  • In the switch case statement first, the condition is evaluated. After evaluating the condition the value is compared with the value of the case which is specified inside the switch block. When the value of condition matches with the case value the block code associated with that case will be executed.
  • If the value of condition does not match with any of the case values then the default block code associated with the default will be executed.

Flowchart:-

Switch Case Flow Chart

Example:-

<? php
	$number = 6;
	switch($number){
		case 1:
			echo "Today is Sunday";
			break;
		case 2:
			echo "Today is Monday";
			break;
		case 3:
			echo "Today is Tuesday";
			break;
		case 4:
			echo "Today is Wednesday";
			break;
		case 5:
			echo "Today is Thursday";
			break;
		case 6:
			echo "Today is Friday";
			break;
		case 7:
			echo "Today is Saturday";
			break;
		default:
			echo "Invalid Day";
			break;
	}
?>

Output:-

Today is Friday