Current Affairs updated daily
KalviGavaniKalviGavani

PHP Conditional Statements Exercise Solutions | KalviGavani

Complete Samacheer Kalvi Class 12 Computer Applications Chapter 6 exercise solutions covering PHP if, if-else, elseif, switch, nested conditionals, comparison operators, and logical operators with detailed code examples and explanations.

Updated 13 June 202626 min read

Exercise Solutions Available

Step-by-step answers for all textbook questions in this chapter

View Solutions →

Chapter 6 — PHP Conditional Statements: Exercise Solutions Guide

How to Use This Page

1. Attempt every exercise question on your own first — use your Samacheer Kalvi textbook and class notes. 2. Compare your answers with the solutions below only after you have written your own. 3. Read the explanations for MCQs and True/False items — understanding why an answer is correct is more important than the answer itself. 4. Practise the short and detailed answers by writing them in your own words; do not memorise verbatim. 5. Use the Exam Checklist at the end for a quick pre-exam revision round.


Key Concepts (Quick Recap)

  • Conditional statements allow the program to make decisions and execute different code blocks based on conditions.
  • The if statement executes a block of code only if a condition is true.
  • The if-else statement executes one block if the condition is true and another block if it is false.
  • The elseif statement checks multiple conditions in sequence; the first true condition's block executes.
  • The switch statement compares a single variable against multiple possible values (cases).
  • Comparison operators: == (equal), === (identical), != (not equal), !== (not identical), >, <, >=, <=.
  • Logical operators: && (AND), || (OR), ! (NOT), and, or, xor.
  • Nested conditionals are if statements inside another if statement; they allow checking multiple levels of conditions.
  • The ternary operator ? : is a shorthand for simple if-else: condition ? value_if_true : value_if_false.
  • In a switch statement, break prevents fall-through to the next case; default handles unmatched cases.
PHP considers these values as
Answerfalse : 0, 0.0, "" (empty string), "0", NULL, false, empty array.
  • Always use curly braces { } to enclose code blocks, even for single-line conditions (best practice).

I. Choose the Best Answer (MCQs)

1. Which conditional statement in PHP executes a block only when a condition is true? (a) if (b) if-else (c) switch (d) for

Answer(a) if The if statement checks a condition and executes the block only when the condition evaluates to true. If the condition is false, the block is skipped entirely.

2. What is the output of the following PHP code?
<?php
  $x = 10;
  if ($x > 5) {
      echo "Greater";
  } else {
      echo "Smaller";
  }
?>
Answer

(a) Smaller (b) Greater (c) Error (d) No output

Answer(b) Greater $x = 10, and 10 > 5 is true, so the if block executes and prints "Greater".

3. Which operator compares both value and type in PHP? (a) == (b) === (c) != (d) <>

Answer(b) === The === (identical) operator returns true only if both the value AND the data type are the same. Example: 10 === "10" is false (integer vs string). == compares only values.

4. What does the elseif statement do? (a) Executes when the first if condition is true (b) Executes when the previous conditions are false and the elseif condition is true (c) Always executes regardless of conditions (d) Ends the conditional block

Answer(b) Executes when the previous conditions are false and the elseif condition is true elseif is checked only when all preceding if and elseif conditions are false. If the elseif condition is true, its block executes and all subsequent conditions are skipped.

5. What is the output of the following code?
<?php
  $day = "Monday";
  switch ($day) {
      case "Monday":
          echo "Start of the week";
          break;
      case "Friday":
          echo "End of the week";
          break;
      default:
          echo "Midweek";
  }
?>
Answer

(a) Start of the week (b) End of the week (c) Midweek (d) Error

Answer(a) Start of the week $day = "Monday" matches the first case, so "Start of the week" is printed. The break prevents fall-through to subsequent cases.

6. What happens if you forget the break statement in a switch case? (a) The switch stops executing (b) The code falls through to the next case and executes it too (c) An error is thrown (d) Only the default case runs

Answer(b) The code falls through to the next case and executes it too Without break, PHP continues executing the code in the next case(s) until it hits a break or the end of the switch. This is called "fall-through."

7. Which logical operator returns true only if BOTH conditions are true?
Answer

(b) ! (c) && (d) xor

(a) ``
Answer(c) &&
The && (AND) operator returns true only when both operands are true. ` (OR) returns true if at least one operand is true. ! (NOT) reverses the value. xor` returns true if exactly one operand is true.

8. What is the output of the following code?
<?php
  $x = 10;
  $y = "10";
  if ($x == $y) {
      echo "Equal";
  } else {
      echo "Not Equal";
  }
?>
Answer

(a) Not Equal (b) Equal (c) Error (d) No output

Answer(b) Equal The == operator compares values only. $x (integer 10) and $y (string "10") have the same value, so the condition is true. === would compare both value and type, giving "Not Equal."

9. The ternary operator in PHP is written as: (a) condition : value1 ? value2 (b) condition ? value1 : value2 (c) condition -> value1 : value2 (d) condition value1 : value2

Answer(b) condition ? value1 : value2 The ternary operator is a shorthand for if-else. If the condition is true, value1 is returned; if false, value2 is returned. Example: $result = ($marks >= 35) ? "Pass" : "Fail";

10. Which of the following values is considered false in PHP? (a) 1 (b) "true" (c) 0 (d) "0false"

Answer(c) 0 In PHP, 0 (integer zero) is considered false. Other false values include: 0.0, "" (empty string), "0", NULL, false, and empty arrays. 1, "true", and "0false" are all truthy.

II. Fill in the Blanks

1. The if statement executes a block of code only when the condition is true. 2. The if-else statement provides two alternative blocks — one for true and one for false. 3. The elseif statement allows checking multiple conditions in sequence. 4. The switch statement compares a variable against multiple possible values. 5. The === operator compares both value and type in PHP. 6. The && operator is the logical AND operator in PHP.

8. The ! operator is the logical NOT operator in PHP. 9. The break statement is used in a switch to prevent fall-through to the next case. 10. The default case in a switch statement handles values that do not match any case.

7. The `` operator is the logical OR operator in PHP.

III. True or False

1. The if statement can exist without an else statement.
AnswerTrue — The else block is optional. An if statement can stand alone, executing its block only when the condition is true.
2. The === operator compares only values in PHP.
AnswerFalse — The === (identical) operator compares both value AND type. The == (equal) operator compares only values.
3. In a switch statement, multiple cases can share the same code block.
AnswerTrue — You can stack multiple case labels before a single code block to execute the same code for different values.
4. The else block is mandatory in an if-else statement.
AnswerFalse — The else block is optional. However, once you use else, it must contain a code block. An if statement without else simply skips execution when the condition is false.
5. The ternary operator can replace any if-else statement.
AnswerFalse — The ternary operator is suitable for simple value assignments. It cannot replace complex if-else blocks with multiple statements. It is best used for concise conditional expressions.
6. 0 and "" (empty string) are both considered false in PHP.
AnswerTrue — In PHP, 0, 0.0, "", "0", NULL, false, and empty arrays are all considered falsy values.
7. A switch statement can use float values as case labels.
AnswerFalse — Switch case labels should be integers, strings, or booleans. Float values as case labels can cause issues due to precision problems and are not recommended.
8. Nested if statements mean an if statement inside another if statement.
AnswerTrue — Nested conditionals are if (or if-else) statements placed inside another if (or else) block, allowing multi-level decision making.
9. The and operator has higher precedence than && in PHP.
AnswerFalse — && has higher precedence than and. They produce the same result but && binds more tightly. $a = true && false gives $a = false, while $a = true and false gives $a = true due to precedence.
10. The default case in a switch statement must always be the last case.
AnswerFalse — The default case can be placed anywhere in the switch, though it is conventionally placed last. If placed earlier, it still only executes when no other case matches.

IV. Match the Following

Set A

Column AColumn B
1. if(c) Executes block when condition is true
2. if-else(a) Chooses between two blocks
3. elseif(e) Checks additional conditions after if
4. switch(b) Compares variable against multiple values
5. ternary(d) Shorthand for simple if-else

Set B

Column AColumn B
1. ==(d) Value comparison
2. ===(a) Value and type comparison
3. !=(b) Not equal
4. &&(e) Logical AND
5. `\\`(c) Logical OR

V. Short Answer Questions

1. Explain the if statement in PHP with an example.
Answer

The if statement executes a block of code only when the specified condition evaluates to true.

Syntax:

if (condition) {
    // Code to execute if condition is true
}

Example 1: Simple if statement

<?php
  $age = 18;
  if ($age >= 18) {
      echo "You are eligible to vote.";
  }
  // Output: You are eligible to vote.
?>

Example 2: If condition with comparison and logical operators

<?php
  $marks = 85;
  if ($marks >= 75 && $marks <= 100) {
      echo "Distinction";
  }
  // Output: Distinction
?>

If the condition is false, the code block is skipped entirely and execution continues after the if block.

2. Differentiate between if-else and elseif with examples.
Answer

if-else provides two alternative paths — one for true and one for false.

<?php
  $age = 16;
  if ($age >= 18) {
      echo "Adult";
  } else {
      echo "Minor";
  }
  // Output: Minor
?>

elseif allows checking multiple conditions in sequence. It is used when there are more than two possible outcomes.

<?php
  $marks = 75;
  if ($marks >= 90) {
      echo "Grade A";
  } elseif ($marks >= 75) {
      echo "Grade B";
  } elseif ($marks >= 60) {
      echo "Grade C";
  } else {
      echo "Grade D";
  }
  // Output: Grade B
?>
Featureif-elseelseif
Number of conditionsTwo (true/false)Multiple conditions
Structureif + elseif + elseif + ... + else
Use caseBinary choiceMultiple alternatives
ExecutionOne of two blocksFirst matching block
3. Explain the switch statement in PHP with an example.
Answer

The switch statement compares a single variable against multiple possible values (cases) and executes the matching case's code block.

Syntax:

switch (variable) {
    case value1:
        // Code for value1
        break;
    case value2:
        // Code for value2
        break;
    default:
        // Code if no case matches
}

Example: Day of the week

<?php
  $day = "Wednesday";
  switch ($day) {
      case "Monday":
          echo "Start of the week";
          break;
      case "Wednesday":
          echo "Midweek";
          break;
      case "Friday":
          echo "End of the week";
          break;
      default:
          echo "Regular day";
  }
  // Output: Midweek
?>

Key points about switch:

  • The variable is compared against each case value using loose comparison (==)
  • break prevents fall-through to the next case
  • default handles values that don't match any case
  • Switch is cleaner than multiple elseif statements when checking one variable against many fixed values
4. What are comparison operators in PHP? List them with examples.
Answer

Comparison operators compare two values and return a boolean (true or false).

OperatorNameExampleResult
==Equal10 == "10"true (same value)
===Identical10 === "10"false (different type)
!=Not equal10 != 20true
<>Not equal10 <> 20true
!==Not identical10 !== "10"true (different type)
>Greater than15 > 10true
<Less than5 < 10true
>=Greater than or equal10 >= 10true
<=Less than or equal5 <= 10true
<?php
  $x = 10;
  $y = "10";

  var_dump($x == $y);   // bool(true)  — values are equal
  var_dump($x === $y);  // bool(false) — types differ (int vs string)
  var_dump($x != $y);   // bool(false) — values are equal
  var_dump($x !== $y);  // bool(true)  — types differ
  var_dump($x > 5);     // bool(true)  — 10 is greater than 5
  var_dump($x <= 10);   // bool(true)  — 10 is equal to 10
?>
5. Explain logical operators in PHP with examples.
Answer

Logical operators combine multiple conditions to form complex boolean expressions.

1. AND (&& or and): Returns true only if both conditions are true.

<?php
  $age = 20;
  $has_id = true;
  if ($age >= 18 && $has_id) {
      echo "Eligible to vote";
  }
  // Output: Eligible to vote
?>

Returns true if at least one condition is true.

**2. OR (` or or`):**
<?php
  $day = "Saturday";
  if ($day == "Saturday" || $day == "Sunday") {
      echo "Weekend!";
  }
  // Output: Weekend!
?>

3. NOT (!): Reverses the boolean value.

<?php
  $is_raining = false;
  if (!$is_raining) {
      echo "Go outside!";
  }
  // Output: Go outside!
?>

4. XOR (xor): Returns true if exactly one condition is true (not both).

<?php
  $a = true;
  $b = false;
  var_dump($a xor $b);  // bool(true) — exactly one is true
  var_dump($a xor $a);  // bool(false) — both are true
?>
Precedence: && has higher precedence than and; ` has higher precedence than or. Always use && and ` for clarity.
OperatorSymbolReturns True When
AND&&Both conditions are true
OR`\\`At least one condition is true
NOT!Condition is false
XORxorExactly one condition is true
6. What is the ternary operator? Give an example.
Answer

The ternary operator ? : is a shorthand way to write simple if-else statements. It is the only PHP operator that takes three operands.

Syntax:

condition ? value_if_true : value_if_false;

Example 1: Pass/Fail

<?php
  $marks = 75;
  $result = ($marks >= 35) ? "Pass" : "Fail";
  echo $result;  // Output: Pass
?>

Equivalent if-else:

<?php
  $marks = 75;
  if ($marks >= 35) {
      $result = "Pass";
  } else {
      $result = "Fail";
  }
  echo $result;  // Output: Pass
?>

Example 2: Even/Odd

<?php
  $num = 7;
  echo ($num % 2 == 0) ? "Even" : "Odd";
  // Output: Odd
?>

Example 3: Nested ternary (use sparingly)

<?php
  $marks = 85;
  $grade = ($marks >= 90) ? "A" : (($marks >= 75) ? "B" : "C");
  echo $grade;  // Output: B
?>

Note: While nested ternary operators are possible, they reduce readability. For complex conditions, use if-elseif-else.


VI. Detailed Answer Questions

1. Explain the if, if-else, and if-elseif-else statements in PHP with syntax and examples.
1. The if Statement:
Answer

The if statement executes a block of code only when the condition is true.

Syntax:

if (condition) {
    // Code to execute if condition is true
}

Example:

<?php
  $temperature = 40;
  if ($temperature > 35) {
      echo "It's very hot today!";
  }
  // Output: It's very hot today!
?>
2. The if-else Statement:
Answer

The if-else statement provides two alternative blocks — one for true and one for false.

Syntax:

if (condition) {
    // Code if condition is true
} else {
    // Code if condition is false
}

Example: Even or Odd

<?php
  $num = 7;
  if ($num % 2 == 0) {
      echo "$num is even";
  } else {
      echo "$num is odd";
  }
  // Output: 7 is odd
?>

Example: Voting eligibility

<?php
  $age = 17;
  if ($age >= 18) {
      echo "Eligible to vote";
  } else {
      echo "Not eligible to vote";
  }
  // Output: Not eligible to vote
?>
3. The if-elseif-else Statement:
Answer

The if-elseif-else statement checks multiple conditions in sequence. The first true condition's block executes; all others are skipped.

Syntax:

if (condition1) {
    // Code if condition1 is true
} elseif (condition2) {
    // Code if condition2 is true
} elseif (condition3) {
    // Code if condition3 is true
} else {
    // Code if all conditions are false
}

Example: Grade calculation

<?php
  $marks = 75;

  if ($marks >= 90) {
      echo "Grade: A (Distinction)";
  } elseif ($marks >= 75) {
      echo "Grade: B (First Class)";
  } elseif ($marks >= 60) {
      echo "Grade: C (Second Class)";
  } elseif ($marks >= 50) {
      echo "Grade: D (Third Class)";
  } elseif ($marks >= 35) {
      echo "Grade: E (Pass)";
  } else {
      echo "Grade: F (Fail)";
  }
  // Output: Grade: B (First Class)
?>

Important points:

  • PHP evaluates conditions from top to bottom
  • Once a true condition is found, its block executes and all remaining conditions are skipped
  • The else block is optional but should be included as a default case
  • You can have any number of elseif blocks

2. Explain the switch statement in PHP with syntax, examples, and the importance of break.
Answer

The switch statement compares a single expression against multiple possible values and executes the matching case's code block.

Syntax:

switch (expression) {
    case value1:
        // Code for value1
        break;
    case value2:
        // Code for value2
        break;
    case value3:
        // Code for value3
        break;
    default:
        // Code if no case matches
        break;
}

Example 1: Calculator

<?php
  $operator = "+";
  $a = 10;
  $b = 5;

  switch ($operator) {
      case "+":
          echo "$a + $b = " . ($a + $b);
          break;
      case "-":
          echo "$a - $b = " . ($a - $b);
          break;
      case "*":
          echo "$a * $b = " . ($a * $b);
          break;
      case "/":
          echo "$a / $b = " . ($a / $b);
          break;
      default:
          echo "Invalid operator";
  }
  // Output: 10 + 5 = 15
?>

Example 2: Day name from number

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

Importance of break:

The break statement stops the switch from executing subsequent cases. Without break, PHP continues executing code in the next case(s) — this is called fall-through.

Fall-through example (without break):

<?php
  $color = "Red";
  switch ($color) {
      case "Red":
          echo "Stop";
          // No break here!
      case "Yellow":
          echo "Caution";
          // No break here!
      case "Green":
          echo "Go";
          break;
  }
  // Output: StopCautionGo (all three cases execute!)
?>

Useful fall-through (intentional stacking of cases):

<?php
  $month = 2;
  switch ($month) {
      case 1: case 3: case 5: case 7:
      case 8: case 10: case 12:
          echo "31 days";
          break;
      case 4: case 6: case 9: case 11:
          echo "30 days";
          break;
      case 2:
          echo "28 or 29 days";
          break;
      default:
          echo "Invalid month";
  }
  // Output: 28 or 29 days
?>

Comparison: switch vs. if-elseif-else:

Featureswitchif-elseif-else
ComparesSingle variable against fixed valuesAny boolean condition
Data typesInteger, string, booleanAny expression
ReadabilityCleaner for many fixed valuesBetter for complex conditions
Fall-throughPossible (use break)Not applicable
Default casedefault blockelse block

3. Explain nested conditional statements with examples.
Answer

Nested conditionals are if (or if-else, elseif) statements placed inside another if statement. They allow multi-level decision making where an inner condition is checked only when the outer condition is true.

Syntax:

if (outer_condition) {
    if (inner_condition) {
        // Code when both conditions are true
    } else {
        // Code when outer is true but inner is false
    }
} else {
    // Code when outer condition is false
}

Example 1: Loan eligibility (nested if-else)

<?php
  $age = 25;
  $salary = 30000;

  if ($age >= 21) {
      if ($salary >= 25000) {
          echo "Eligible for loan";
      } else {
          echo "Salary too low for loan";
      }
  } else {
      echo "Age too low for loan";
  }
  // Output: Eligible for loan
?>

Example 2: Student result with grade (nested if)

<?php
  $marks = 72;

  if ($marks >= 35) {
      echo "Result: Pass<br>";
      if ($marks >= 90) {
          echo "Grade: A";
      } elseif ($marks >= 75) {
          echo "Grade: B";
      } elseif ($marks >= 60) {
          echo "Grade: C";
      } else {
          echo "Grade: D";
      }
  } else {
      echo "Result: Fail";
  }
  // Output: Result: Pass  Grade: C
?>

Example 3: Number classification

<?php
  $num = -7;

  if ($num > 0) {
      echo "Positive number";
      if ($num % 2 == 0) {
          echo " and Even";
      } else {
          echo " and Odd";
      }
  } elseif ($num < 0) {
      echo "Negative number";
      if ($num % 2 == 0) {
          echo " and Even";
      } else {
          echo " and Odd";
      }
  } else {
      echo "Zero";
  }
  // Output: Negative number and Odd
?>

Best practices for nested conditionals: 1. Avoid deep nesting (more than 3 levels) — it makes code hard to read 2. Use logical operators to combine conditions where possible 3. Consider using switch for multiple fixed-value comparisons 4. Always use curly braces { } to clearly define code blocks

Flattening nested conditions:

<?php
  // Nested version
  if ($age >= 21) {
      if ($salary >= 25000) {
          echo "Eligible";
      }
  }

  // Flattened version using logical AND
  if ($age >= 21 && $salary >= 25000) {
      echo "Eligible";
  }
?>

4. Compare if-elseif-else and switch statements with examples.
Answer

if-elseif-else vs. switch:

Featureif-elseif-elseswitch
Condition typeAny boolean expressionCompares single variable against fixed values
Data typesAny (numbers, strings, booleans, expressions)Integers, strings, booleans only
ComparisonUses all comparison operators (==, ===, >, <, etc.)Uses loose comparison (==) only
Range conditionsCan check ranges ($x > 10 && $x < 20)Cannot check ranges directly
Multiple conditionsCan combine with logical operators (&&, ``)Each case checks one value
Fall-throughNot possiblePossible if break is omitted
ReadabilityBetter for complex conditionsBetter for many fixed-value comparisons
Default handlingelse blockdefault case
PerformanceChecks conditions sequentiallyMay use optimised jump tables

When to use if-elseif-else:

  • Checking ranges: if ($marks >= 90), if ($age > 18 && $age < 60)
  • Complex boolean expressions: if ($x > 0 && $y < 100)
  • Different types of conditions: if ($a > $b), if (strlen($name) > 5)

When to use switch:

  • Comparing one variable against many fixed values: days of the week, menu choices, operator symbols
  • Cleaner code for many specific values
  • When fall-through behaviour is useful (stacking cases)

Example: Same logic using both approaches

Using if-elseif-else:

<?php
  $day = "Tuesday";
  if ($day == "Monday") {
      echo "Start of the week";
  } elseif ($day == "Tuesday") {
      echo "Second day";
  } elseif ($day == "Wednesday") {
      echo "Midweek";
  } elseif ($day == "Thursday") {
      echo "Almost Friday";
  } elseif ($day == "Friday") {
      echo "End of work week";
  } elseif ($day == "Saturday" || $day == "Sunday") {
      echo "Weekend";
  } else {
      echo "Invalid day";
  }
?>

Using switch:

<?php
  $day = "Tuesday";
  switch ($day) {
      case "Monday":
          echo "Start of the week";
          break;
      case "Tuesday":
          echo "Second day";
          break;
      case "Wednesday":
          echo "Midweek";
          break;
      case "Thursday":
          echo "Almost Friday";
          break;
      case "Friday":
          echo "End of work week";
          break;
      case "Saturday":
      case "Sunday":
          echo "Weekend";
          break;
      default:
          echo "Invalid day";
  }
?>

Important note: The switch uses == (loose comparison). For strict comparison (===), you must use if-elseif-else.


5. Write PHP programs to solve the following problems using conditional statements.
Answer

Program 1: Find the largest of three numbers

<?php
  $a = 25;
  $b = 47;
  $c = 18;

  if ($a > $b && $a > $c) {
      echo "$a is the largest number";
  } elseif ($b > $a && $b > $c) {
      echo "$b is the largest number";
  } else {
      echo "$c is the largest number";
  }
  // Output: 47 is the largest number
?>

Program 2: Check if a year is a leap year

<?php
  $year = 2024;

  if ($year % 400 == 0) {
      echo "$year is a leap year";
  } elseif ($year % 100 == 0) {
      echo "$year is not a leap year";
  } elseif ($year % 4 == 0) {
      echo "$year is a leap year";
  } else {
      echo "$year is not a leap year";
  }
  // Output: 2024 is a leap year
?>

Leap year rules:

  • Divisible by 400 → leap year
  • Divisible by 100 (but not 400) → not a leap year
  • Divisible by 4 (but not 100) → leap year
  • Otherwise → not a leap year

Program 3: Simple calculator using switch

<?php
  $num1 = 20;
  $num2 = 5;
  $operator = "*";
  $result = 0;

  switch ($operator) {
      case "+":
          $result = $num1 + $num2;
          echo "$num1 + $num2 = $result";
          break;
      case "-":
          $result = $num1 - $num2;
          echo "$num1 - $num2 = $result";
          break;
      case "*":
          $result = $num1 * $num2;
          echo "$num1 * $num2 = $result";
          break;
      case "/":
          if ($num2 != 0) {
              $result = $num1 / $num2;
              echo "$num1 / $num2 = $result";
          } else {
              echo "Error: Division by zero";
          }
          break;
      case "%":
          $result = $num1 % $num2;
          echo "$num1 % $num2 = $result";
          break;
      default:
          echo "Invalid operator";
  }
  // Output: 20 * 5 = 100
?>

Program 4: Student result with grade assignment

<?php
  $name = "Arun";
  $marks = 85;

  echo "Student: $name<br>";
  echo "Marks: $marks<br>";

  if ($marks >= 35) {
      echo "Result: Pass<br>";

      if ($marks >= 90) {
          echo "Grade: A (Distinction)";
      } elseif ($marks >= 75) {
          echo "Grade: B (First Class)";
      } elseif ($marks >= 60) {
          echo "Grade: C (Second Class)";
      } elseif ($marks >= 50) {
          echo "Grade: D (Third Class)";
      } else {
          echo "Grade: E (Pass)";
      }
  } else {
      echo "Result: Fail<br>";
      echo "Grade: F";
  }
  // Output:
  // Student: Arun
  // Marks: 85
  // Result: Pass
  // Grade: B (First Class)
?>

Program 5: Check whether a number is positive, negative, or zero

<?php
  $num = -5;

  if ($num > 0) {
      echo "$num is a positive number";
  } elseif ($num < 0) {
      echo "$num is a negative number";
  } else {
      echo "The number is zero";
  }
  // Output: -5 is a negative number
?>

Common Mistakes

1. Using = instead of == in conditions — if ($x = 5) assigns 5 to $x and is always true. Use if ($x == 5) for comparison.

2. Forgetting break in switch statements — Without break, execution falls through to subsequent cases, producing unexpected output. Always include break after each case.

3. Confusing == and === — 10 == "10" is true (values match), but 10 === "10" is false (types differ). Know which comparison you need.

4. Missing curly braces for multi-line blocks — While PHP allows single-line if statements without braces, omitting braces for multi-line blocks causes logic errors. Always use { }.

5. Using elseif as two words (else if) — Both work, but elseif (one word) is the standard PHP syntax. else if (two words) behaves slightly differently in nested contexts.

6. Not handling the default case in switch — Always include a default case to handle unexpected values. Without it, invalid inputs produce no output or errors.

7. Deep nesting of conditionals — More than 3 levels of nesting makes code hard to read. Flatten using logical operators or switch where possible.


Exam Checklist

  • [ ] Can write if, if-else, and if-elseif-else statements with correct syntax
  • [ ] Understand when to use switch vs. if-elseif-else
  • [ ] Know all comparison operators (==, ===, !=, !==, >, <, >=, <=)
  • [ ] Know all logical operators (&&, ||, !, and, or, xor)
  • [ ] Can write nested conditional statements and trace their output
  • [ ] Understand the importance of break in switch statements
  • [ ] Can use the ternary operator for simple conditions
  • [ ] Know PHP's falsy values (0, 0.0, "", "0", NULL, false, empty array)
  • [ ] Can write PHP programs: largest of three numbers, leap year, calculator, grade assignment
  • [ ] Can differentiate between == (loose) and === (strict) comparison

Frequently Asked Questions

Conditional statements allow PHP to execute different code blocks based on whether a condition is true or false. PHP supports if, if-else, elseif, and switch statements.