For any queries you can reach us at infovistarindia@gmail.com / WhatsApp us: +919158876092

PHP if-else

Overview

Conditional statements are used to execute various operations based on different conditions. There are multiple ways to use conditional statements in PHP.

  • if
  • if-else
  • if-else-if

if statement

if statement executes code if a condition is true.

Syntax:

if (condition) {
  	code to be executed if condition is true;
}

Example:

$a = 10;
$b = 50;
if($a < $b) {
	echo $a.“ is less than ”.$b;
}

if-else statement

This statement executes a set of codes when a condition is true and another if the condition is false.

Syntax:

if (condition) {
  	code to be executed if condition is true;
} else {
  	code to be executed if condition is false;
}

Example:

$a = 60;
$b = 50;
if($a < $b) {
	echo $a.“ is less than ”.$b;
} else {
	echo $a.“ is greater than ”.$b;
}

if-elseif-else statement

The switch statement is used to execute code based on multiple conditions. It works identical to a PHP if-else-if statement.

Syntax:

switch (n) {
  	case label1:
    		code to be executed if n=label1;
    		break;
  	case label2:
    		code to be executed if n=label2;
    		break;
 	case label3:
    		code to be executed if n=label3;
    		break;
  	default:
    		code to be executed if n is different from all labels;
}
  • The default is an optional statement.
  • There can be just one default in a switch statement.
  • Each case can have a break statement, which is used to terminate the sequence of statements.

Example:

$color = "green";
switch ($color) {
  	case "red":
    		echo "Your favorite color is red!";
    		break;
  	case "green":
    		echo "Your favorite color is green!";
    		break;
  	case "blue":
    		echo "Your favorite color is blue!";
    		break;
  	default:
    		echo "Your favorite color is neither red, green, nor blue!";
}