PHP Conditional Statements
# Chapter 7: PHP Conditional Statements
1. Introduction
Welcome to Chapter 7! So far, our PHP scripts have executed every single line of code from top to bottom. But real applications need to make decisions. If a user enters the correct password, log them in; otherwise, show an error. If a student's score is above 50, they pass; otherwise, they fail. Conditional statements give your code a "brain," allowing it to execute different blocks of code based on different conditions.2. Learning Objectives
By the end of this chapter, you will be able to:-
Use
ifstatements to execute code when a condition is true.
-
Use
elseto provide a fallback when the condition is false.
-
Chain multiple conditions together using
elseif.
-
Use the
switchstatement for evaluating a single variable against many possible values.
- Apply conditional logic to real-world scenarios.
3. The if Statement
The if statement is the most basic conditional. It evaluates a condition (inside parentheses), and if that condition evaluates to true, it executes the code block (inside curly braces).
4. The else Statement
What if we want something to happen when the condition is false? We attach an else block to the end of our if statement.
5. The elseif Statement
When you have more than two possibilities, you can use elseif (or else if) to check multiple conditions in sequence.
6. The switch Statement
If you find yourself writing a massive chain of elseif statements checking the exact same variable against different values, a switch statement is cleaner and faster.
*Note: The break keyword stops the switch block from continuing to run the code in the cases below it. default acts like the final else fallback.*
7. Real-World Examples
Imagine an e-commerce checkout system checking shipping costs based on the country.8. Output Explanations
In the shipping example, PHP checks the first condition ($country == "USA"). Since it is false, it moves to the elseif. It checks if the country is Canada OR Mexico. Since $country is "Canada", this condition is true. It executes the block, setting $shipping_cost to 15.00, skips the else block entirely, and proceeds to echo the final cost.
9. Common Mistakes
-
Using assignment
=instead of comparison==: Writingif ($x = 10)will actually *assign* 10 to$x, and the condition will evaluate to true regardless of what$xoriginally was! Always use==or===.
-
Forgetting curly braces: While PHP allows omitting curly braces for single-line
ifstatements, it is highly prone to bugs. Always use{ }.
-
Forgetting
breakin aswitch: If you forgetbreak, PHP will execute the matched case AND every single case below it (known as fall-through).
10. Best Practices
-
Early Return/Bail Early: If testing for errors, put them at the top of your script. If there is an error, stop the script, reducing the need for massively nested
ifstatements.
-
Strict Comparison: Use
===instead of==to prevent unexpected type juggling bugs.
11. Exercises
-
1.
Write an
if/elsestatement that checks if a$temperaturevariable is above 30. Output "It's hot" if true, "It's cold" if false.
-
2.
Write a
switchstatement that takes a variable$day = "Monday"and echoes whether it is a weekday or weekend.
12. Mini Project: Grade Checker
Task: Build a script that takes a numerical student score and assigns a letter grade based on specific ranges.13. Coding Challenges
Challenge 1: Create an access control script. Variables:$age and $has_id. An if statement should check: If age is 18 or older AND they have an ID (true), echo "Access Granted". Otherwise, echo "Access Denied".
14. MCQs with Answers
1. What happens if anif condition is false and there is no else block?
A) PHP throws a fatal error.
B) PHP skips the if block and continues executing the rest of the script.
C) PHP crashes the server.
D) The script stops executing immediately.
*Answer: B*
2. Which keyword stops a switch block from evaluating the remaining cases?
A) stop
B) end
C) exit
D) break
*Answer: D*
3. Why is if ($x = 5) dangerous?
A) It causes a syntax error.
B) It assigns 5 to $x instead of comparing it, always resulting in true.
C) It deletes the variable $x.
D) It only works with strings.
*Answer: B*
15. Interview Questions
Q: When should you use aswitch statement instead of if/elseif/else?
*A:* You should use a switch statement when you are comparing a single variable against many different literal values (like checking a specific user role, a status code, or days of the week). It makes the code much cleaner and easier to read than a massive chain of elseifs.
Q: What is the Ternary Operator in PHP?
*A:* It is a shorthand way of writing a simple if/else statement on a single line. The syntax is condition ? true_value : false_value. Example: $status = ($age >= 18) ? "Adult" : "Minor";
16. FAQs
Q: Can I nest anif statement inside another if statement?
*A:* Yes, absolutely! This is called "nesting." However, try to avoid nesting too deep (more than 2 or 3 levels), as it makes your code very difficult to read.
17. Summary
You've given your code a brain! You learned how to useif, else, and elseif to make complex logical decisions based on changing conditions. You also learned how to use the switch statement to efficiently route logic when checking a single variable against many possibilities.