Introductions
PHP provides different ways to control the flow of a program based on conditions. The switch statement is useful when one variable needs to be compared against multiple possible values. A nested if statement allows you to check a condition inside another if or else block. In this chapter, you will practise both concepts through PHP Switch and Nested If Statements Practice Questions with Solutions to help you build concepts.
Question 1: Display a Day Name Using a Switch Statement
Problem Statement
Write a PHP program that stores a number from 1 to 7 and displays the corresponding day of the week using a switch statement. Display an appropriate message if the number is outside the valid range.
PHP Solution
<?php
$dayNumber = 3;
switch ($dayNumber) {
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";
}
?>
Sample Output
Wednesday
Explanation
The variable $dayNumber contains the value 3. PHP compares it with each case value and executes the matching block. Since 3 matches case 3, the program displays Wednesday.
The break statement stops execution from continuing into the following cases. The default block runs when no case matches.
Concepts Covered
switchstatementcaseandbreakdefaultblock- Conditional program flow
Question 2: Create a Simple Calculator Using Switch
Problem Statement
Write a PHP program that performs addition, subtraction, multiplication, or division based on the selected operator. Use a switch statement to select the operation and handle division by zero.
PHP Solution
<?php
$num1 = 20;
$num2 = 5;
$operator = "/";
switch ($operator) {
case "+":
echo "Result: " . ($num1 + $num2);
break;
case "-":
echo "Result: " . ($num1 - $num2);
break;
case "*":
echo "Result: " . ($num1 * $num2);
break;
case "/":
if ($num2 != 0) {
echo "Result: " . ($num1 / $num2);
} else {
echo "Cannot divide by zero";
}
break;
default:
echo "Invalid operator";
}
?>
Sample Output
Result: 4
Explanation
The program stores two numbers and the operator in variables. The switch statement checks the operator and selects the matching mathematical operation.
Here, the operator is /, so PHP divides 20 by 5. Before division, an if statement checks whether the second number is zero. This prevents an invalid division.
Concepts Covered
switchstatement- Arithmetic operators
- Nested
ifstatement - Division-by-zero handling
defaultcase
Question 3: Display a Message Based on a Traffic Light Color
Problem Statement
Create a PHP program that stores a traffic light color and displays the appropriate instruction:
- Red: Stop
- Yellow: Get Ready
- Green: Go
- Any other color: Invalid traffic light color
Use a switch statement.
PHP Solution
<?php
$lightColor = "green";
switch ($lightColor) {
case "red":
echo "Stop";
break;
case "yellow":
echo "Get Ready";
break;
case "green":
echo "Go";
break;
default:
echo "Invalid traffic light color";
}
?>
Sample Output
Go
Explanation
The switch statement compares $lightColor against the listed color values. Since the variable contains "green", the program displays Go.
String comparisons in these cases are case-sensitive. For example, "green" and "Green" are different strings. You can normalize user input with functions such as strtolower() if you want to accept different letter cases.
Concepts Covered
- Switching on string values
casestatementsbreakstatement- Default handling
- Case-sensitive string comparisons
Question 4: Calculate a Discount Based on Customer Type
Problem Statement
A shop offers different discounts based on customer type:
- Regular customer: 5%
- Silver customer: 10%
- Gold customer: 15%
- Platinum customer: 20%
Write a PHP program that uses a switch statement to calculate the discount and final bill amount.
PHP Solution
<?php
$customerType = "Gold";
$billAmount = 2000;
$discountRate = 0;
switch ($customerType) {
case "Regular":
$discountRate = 5;
break;
case "Silver":
$discountRate = 10;
break;
case "Gold":
$discountRate = 15;
break;
case "Platinum":
$discountRate = 20;
break;
default:
echo "Invalid customer type";
exit;
}
$discountAmount = ($billAmount * $discountRate) / 100;
$finalAmount = $billAmount - $discountAmount;
echo "Customer Type: " . $customerType . "\n";
echo "Bill Amount: " . $billAmount . "\n";
echo "Discount: " . $discountAmount . "\n";
echo "Final Amount: " . $finalAmount;
?>
Sample Output
Customer Type: Gold
Bill Amount: 2000
Discount: 300
Final Amount: 1700
Explanation
The switch statement assigns a discount percentage according to the customer type. A Gold customer receives a 15% discount.
The program calculates the discount amount by multiplying the bill by the discount rate and dividing by 100. It then subtracts the discount from the original bill.
The exit statement stops the program if the customer type is invalid.
Concepts Covered
switchstatement- Customer categories
- Percentage calculations
- Variables and arithmetic
- Invalid input handling
Question 5: Check Login Details Using Nested If Statements
Problem Statement
Write a PHP program that checks a user’s username and password. If the username is correct, check the password. Display a success message only when both are correct.
Use nested if statements.
PHP Solution
<?php
$username = "admin";
$password = "admin123";
$enteredUsername = "admin";
$enteredPassword = "admin123";
if ($enteredUsername == $username) {
if ($enteredPassword == $password) {
echo "Login successful";
} else {
echo "Incorrect password";
}
} else {
echo "Incorrect username";
}
?>
Sample Output
Login successful
Explanation
The first if statement checks whether the entered username matches the stored username.
Only when the username is correct does PHP enter the first block and check the password using another if statement. This second condition is nested inside the first one.
If either value is incorrect, the program displays the corresponding message.
Note: This is a learning example. Real applications should store passwords securely using password hashing and verify them with PHP’s password functions rather than comparing plain-text passwords.
Concepts Covered
- Nested
ifstatements - Nested
elseblocks - String comparison
- Multiple condition checks
- Login validation basics
Question 6: Check Student Eligibility for an Exam
Problem Statement
A student is eligible to sit for an exam only if their attendance is at least 75%. If attendance is sufficient, check whether the student has paid the examination fee. Display the appropriate result using nested if statements.
PHP Solution
<?php
$attendance = 82;
$feePaid = true;
if ($attendance >= 75) {
if ($feePaid == true) {
echo "Student is eligible for the exam";
} else {
echo "Please pay the examination fee";
}
} else {
echo "Student is not eligible due to low attendance";
}
?>
Sample Output
Student is eligible for the exam
Explanation
The outer if statement checks whether attendance is at least 75%. If this condition is true, the inner if checks whether the examination fee has been paid.
The student is eligible only when both conditions are satisfied. If attendance is below 75%, PHP executes the outer else block without checking the fee condition.
Concepts Covered
- Nested
ifstatements - Comparison operators
- Boolean values
- Attendance validation
- Multiple eligibility conditions
Question 7: Check Employee Bonus Eligibility Using Nested If
Problem Statement
A company considers employees for a bonus if their performance rating is at least 4 out of 5. Employees who meet this requirement receive a bonus only if they have completed at least two years of service.
Write a PHP program using nested if statements.
PHP Solution
<?php
$performanceRating = 4.5;
$yearsOfService = 3;
if ($performanceRating >= 4) {
if ($yearsOfService >= 2) {
echo "Employee is eligible for a bonus";
} else {
echo "Performance is good, but service period is insufficient";
}
} else {
echo "Employee does not meet the performance requirement";
}
?>
Sample Output
Employee is eligible for a bonus
Explanation
The outer condition checks the employee’s performance rating. If the rating is at least 4, PHP checks the employee’s years of service through the nested if statement.
The employee qualifies only when both conditions are satisfied. If the performance rating is too low, the service period is not checked.
Concepts Covered
- Nested conditions
- Comparison operators
- Employee eligibility rules
- Numeric variables
- Business logic
Question 8: Determine a Product Category Using Switch and Nested If
Problem Statement
A store classifies products as Electronics, Clothing, or Grocery. Use a switch statement to identify the product category. For Electronics, use a nested if statement to check whether the price is at least 10,000 and display a suitable message.
PHP Solution
<?php
$productCategory = "Electronics";
$productPrice = 15000;
switch ($productCategory) {
case "Electronics":
if ($productPrice >= 10000) {
echo "Premium electronic product";
} else {
echo "Standard electronic product";
}
break;
case "Clothing":
echo "Clothing product";
break;
case "Grocery":
echo "Grocery product";
break;
default:
echo "Unknown product category";
}
?>
Sample Output
Premium electronic product
Explanation
The switch statement first checks the product category. When the category is Electronics, PHP executes the corresponding case.
Inside that case, a nested if statement checks the price. Since the price is 15,000, which is at least 10,000, the program displays Premium electronic product.
For Clothing and Grocery, the program displays the category message without checking the price.
Concepts Covered
- Combining
switchand nestedif - Product categorization
- Price comparison
- Conditional program flow
- Business rules
Question 9: Create a Menu-Driven Program Using Switch
Problem Statement
Create a simple menu-driven PHP program using a switch statement. The menu should allow a user to select one of the following options:
- Display a welcome message
- Display the current PHP version
- Display a farewell message
Use a variable to simulate the selected menu option.
PHP Solution
<?php
$choice = 2;
switch ($choice) {
case 1:
echo "Welcome to PHP programming";
break;
case 2:
echo "PHP Version: " . PHP_VERSION;
break;
case 3:
echo "Thank you for using this program";
break;
default:
echo "Invalid menu option";
}
?>
Sample Output
The exact version number depends on the PHP environment. For example:
PHP Version: 8.3.0
Explanation
The variable $choice represents the user’s selected menu option. In this example, its value is 2, so the program displays the PHP version using the built-in PHP_VERSION constant.
In a command-line or web application, you could obtain the choice from user input or a form. This example uses a fixed value to focus on the switch statement.
Concepts Covered
- Menu-driven program logic
switch,case, anddefault- PHP built-in constants
- Selection-based execution
- Basic program design
Question 10: Check Loan Eligibility Using Switch and Nested If
Problem Statement
Create a PHP program that checks a person’s loan eligibility based on employment type and monthly income.
Use these rules:
- Salaried employees must earn at least ₹25,000 per month.
- Self-employed applicants must earn at least ₹40,000 per month.
- If the applicant meets the income requirement, check whether their credit score is at least 700.
- Other employment types are not supported by this example.
Use a switch statement for employment type and nested if statements for the eligibility checks.
PHP Solution
<?php
$employmentType = "Salaried";
$monthlyIncome = 35000;
$creditScore = 750;
switch ($employmentType) {
case "Salaried":
if ($monthlyIncome >= 25000) {
if ($creditScore >= 700) {
echo "Applicant meets the example loan eligibility rules";
} else {
echo "Credit score is below the required level";
}
} else {
echo "Monthly income is below the required level";
}
break;
case "Self-employed":
if ($monthlyIncome >= 40000) {
if ($creditScore >= 700) {
echo "Applicant meets the example loan eligibility rules";
} else {
echo "Credit score is below the required level";
}
} else {
echo "Monthly income is below the required level";
}
break;
default:
echo "Employment type is not supported";
}
?>
Sample Output
Applicant meets the example loan eligibility rules
Explanation
The switch statement selects the income requirement based on the applicant’s employment type.
For a Salaried applicant, the program checks whether the monthly income is at least ₹25,000. If it is, another nested if checks whether the credit score is at least 700.
The applicant in this example meets both conditions. These rules are for programming practice only and do not represent the actual eligibility criteria of any bank or lender.
Concepts Covered
switchstatement- Nested
ifstatements - Income and credit score comparisons
- Multiple eligibility rules
- Practical conditional logic
Key Takeaways
- A
switchstatement selects a code block based on the value of an expression. - The
casekeyword defines a possible matching value. - The
breakstatement prevents execution from continuing into subsequent cases. - The
defaultblock handles values that do not match any case. - A nested
ifstatement places one conditional statement inside another. - Nested conditions are useful when one check should happen only after another condition is satisfied.
- You can combine
switchand nestedifstatements to solve more complex problems. - Always handle invalid input and important edge cases in your programs.
- For larger programs, consider whether a simpler condition or a separate function would make the code easier to maintain.
Frequently Asked Questions (FAQs)
1. What is a switch statement in PHP?
A switch statement selects one block of code from several alternatives by comparing an expression with different case values.
2. What is a nested if statement in PHP?
A nested if statement is an if statement placed inside another if or else block. It allows a program to check additional conditions when required.
3. What is the purpose of break in a switch statement?
The break statement exits the current switch block after a matching case has executed. Without it, PHP can continue executing the following cases.
4. What does default do in a switch statement?
The default block runs when none of the defined cases matches the switch expression. It is useful for handling unexpected or invalid values.
5. Can we use an if statement inside a switch statement?
Yes. You can use an if, if-else, or nested if statement inside a case block to check additional conditions.
6. Can we use a switch statement inside an if statement?
Yes. A switch statement can be placed inside an if or else block whenever the program needs to make another selection.
7. What is the difference between switch and if-else?
A switch statement is convenient when one expression is compared against several possible values. An if-else structure is more flexible for ranges, combined conditions, and comparisons such as >=, <=, and logical expressions.
8. Can nested if statements have multiple levels?
Yes. You can place several conditional statements inside one another. However, too many levels can make code difficult to read, so consider simplifying the logic or using separate functions.
9. Is the default case compulsory in PHP switch statements?
No. The default case is optional. However, it is often useful because it allows the program to handle unexpected values.
10. When should I use switch instead of nested if?
Use switch when one expression needs to be matched against several specific values. Use nested if statements when one condition must be checked before another or when the rules involve ranges and complex comparisons.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
