PHP Nested if, else, else-if statements


In PHP, nested if, else, and elseif statements are used to handle complex decision-making scenarios by placing one or more if-else or elseif statements inside another if or else block. This allows you to evaluate multiple conditions in a hierarchical manner.

Basic Structure

Nested if Statements

An if statement inside another if statement is called a nested if statement.

Syntax:

if (condition1) { // Code to be executed if condition1 is true if (condition2) { // Code to be executed if condition2 is true } else { // Code to be executed if condition2 is false } } else { // Code to be executed if condition1 is false }

Example:

<?php $age = 25; $hasID = true; if ($age >= 18) { if ($hasID) { echo "You can enter the club."; } else { echo "You need an ID to enter."; } } else { echo "You are too young to enter."; } ?>

Explanation:

  • The outer if checks if $age is 18 or older.
  • If true, the inner if checks if $hasID is true.
  • Depending on whether $hasID is true or false, the appropriate message is displayed.
  • If the outer if condition is false (i.e., the person is younger than 18), the else block of the outer if is executed.

Nested if-else Statements

You can also nest if-else statements where an else block contains another if-else statement.

Syntax:

if (condition1) { // Code to be executed if condition1 is true } else { if (condition2) { // Code to be executed if condition2 is true } else { // Code to be executed if condition2 is false } }

Example:

<?php $score = 75; if ($score >= 80) { echo "Grade: A"; } else { if ($score >= 60) { echo "Grade: B"; } else { echo "Grade: C"; } } ?>

Explanation:

  • The outer if checks if $score is 80 or more, assigning grade A if true.
  • If the outer condition is false, the nested if-else statement evaluates whether $score is 60 or more to assign grade B, or otherwise assigns grade C.

Nested if-elseif-else Statements

if-elseif-else statements can also be nested inside each other to handle more complex logic.

Syntax:

if (condition1) { // Code to be executed if condition1 is true } elseif (condition2) { // Code to be executed if condition2 is true if (condition3) { // Code to be executed if condition3 is true } else { // Code to be executed if condition3 is false } } else { // Code to be executed if both condition1 and condition2 are false }

Example:

<?php $score = 85; if ($score >= 90) { echo "Grade: A"; } elseif ($score >= 80) { if ($score >= 85) { echo "Grade: B+"; } else { echo "Grade: B"; } } else { echo "Grade: C or below"; } ?>

Explanation:

  • The outer if checks if $score is 90 or more, assigning grade A if true.
  • The elseif block checks if $score is 80 or more and contains another if to further categorize scores into B+ or B based on whether the score is 85 or more.
  • If neither condition is met, it assigns "Grade: C or below."