Topics Covered in This PHP & MySQL Tutorial:
If/Else Statements, Elseif Statements, Switch Statements, Comparison Operators, Logical Operators, the Difference Between == & ===
Exercise Overview
Conditional statements form the backbone of decision-making in programming and will become one of your most frequently used tools as a developer. These control structures allow your code to respond intelligently to different scenarios—executing specific blocks of code when certain conditions are met. Mastering conditionals is essential for creating dynamic, responsive applications that can handle real-world complexity. In this tutorial, you'll learn how to implement PHP's conditional operators through practical, hands-on examples that mirror common development scenarios.
Conditional operators will be one of the most-used elements of your programming life. They enable programs to make decisions and respond dynamically to different situations.
If/Else Statements
The if/else statement represents the fundamental building block of conditional logic in programming. This versatile construct allows your application to branch into different execution paths based on whether a condition evaluates to true or false. Understanding this concept thoroughly will serve as the foundation for more complex logical operations throughout your PHP development career.
The basic syntax for a PHP if statement follows this structure:
if (something is true) {
do something
}
In your code editor, open ifelse.php from the phpclass folder.
Let's create two simple variables and test for equality. Between the
<body>tags, add the following code:<?php $a = 8; $b = 8; if ($a == $b) { echo "a is equal to b"; } ?>This code demonstrates a crucial distinction in PHP: we use a single = sign for assignment (setting variable values) and double == for comparison (testing equality). The triple === operator tests for both value and type equality—a concept we'll explore in detail later in this tutorial.
Save the file and navigate to it in your browser:
- Mac: localhost:8888/phpclass/ifelse.php
- Windows: localhost/phpclass/ifelse.php
You should see the output: a is equal to b.
Now let's observe what happens when our condition evaluates to false. Return to your code editor.
Modify the value of
$ato create an inequality:$a = 20; $b = 8;Save and refresh your browser. You'll notice the page appears blank because the condition
$a == $bnow evaluates to false, and there's no alternative code to execute.Return to your code editor to add the else clause.
Implement an else statement to handle the false condition:
if ($a == $b) { echo "a is equal to b"; } else { echo "a does not equal b"; }Save and refresh your browser. The page now displays a does not equal b, demonstrating how the else block provides a fallback execution path when the initial condition fails.
Building Your First If Statement
Create Variables
Set up test variables with values to compare. Use single equals sign for assignment.
Write Condition
Use double equals sign to test equality. Place condition inside parentheses.
Define Action
Place code to execute inside curly braces. This runs only when condition is true.
Add Else Clause
Provide alternative action when condition is false. Ensures something always happens.
Remember: single equals (=) assigns values, double equals (==) compares values. Mixing these up is a common beginner mistake.
Elseif Statements
While if/else statements handle binary decisions effectively, real-world applications often require more nuanced logic. The elseif statement extends conditional logic by allowing you to test multiple specific conditions in sequence, creating more sophisticated decision trees that better reflect complex business requirements.
Return to your code editor to enhance our conditional logic.
Insert an elseif statement between the existing if and else blocks:
if ($a == $b) { echo "a is equal to b"; } elseif ($a > $b) { echo "a is greater than b"; } else { echo "a does not equal b"; }Save and refresh your browser. The elseif condition now executes, displaying a is greater than b. Notice how PHP evaluates conditions sequentially—once a true condition is found, subsequent conditions are skipped, making elseif chains both efficient and predictable.
If vs Elseif vs Else
| Feature | Statement Type | Usage | Execution Order |
|---|---|---|---|
| if | First condition | Tests primary condition | Executes first if true |
| elseif | Additional conditions | Tests secondary conditions | Executes if previous conditions false |
| else | Default action | Catches all other cases | Executes if all conditions false |
Switch Statements
When you need to compare a single variable against multiple possible values, switch statements offer a cleaner, more readable alternative to lengthy elseif chains. This approach is particularly valuable in scenarios like navigation systems, user role management, or API endpoint routing where you're matching against discrete values rather than ranges or complex conditions.
Let's implement a practical navigation scenario that demonstrates switch statement functionality:
Return to your code editor for a fresh example.
Replace all content between the
<?php ?>tags with this navigation logic:$nav = "home"; switch ($nav) { case "home": echo "Take me to the home page."; break; case "news": echo "Take me to the news section."; break; case "about": echo "Take me to the about page."; break; }Understanding the switch statement components:
$navserves as the control variable that determines which case executesswitch ($nav)initiates the comparison processcase "home":defines a specific value to match againstbreak;prevents "fall-through" behavior—without it, PHP would execute all subsequent cases regardless of their conditions
Save and refresh your browser to see: Take me to the home page.
Test different navigation values by changing the variable:
$nav = "news";Save and refresh to confirm the output changes to: Take me to the news section.
Now test an undefined value to see what happens:
$nav = "sports";Save and refresh—you'll see a blank page because no case matches "sports" and there's no fallback option.
Return to your editor to implement a default case.
Add a default case to handle unmatched values:
switch ($nav) { case "home": echo "Take me to the home page."; break; case "news": echo "Take me to the news section."; break; case "about": echo "Take me to the about page."; break; default: echo "Please choose a page."; break; }Save and refresh to see the default message: Please choose a page. This pattern ensures your application gracefully handles unexpected input values.
Switch vs Multiple Elseif
Always include break statements in switch cases. Without them, PHP will execute every case after the matched one, causing unexpected behavior.
Advanced Comparison Operators
PHP provides a comprehensive set of comparison operators that extend far beyond simple equality testing. These operators enable you to create sophisticated conditional logic for data validation, user authentication, and business rule implementation. Let's explore the inequality operator as our next example.
Return to your code editor for a new demonstration.
Replace the existing PHP code with this inequality test:
$a = 3; $b = 4; if ($a != $b) echo "a does not equal b.";This example introduces two important concepts: the != (not equal) operator and PHP's shorthand if syntax. When your conditional block contains only a single statement, you can omit the curly braces for more concise code—though many development teams prefer explicit braces for consistency and readability.
Save and refresh your browser to confirm the output: a does not equal b.
Essential Comparison Operators
Equality Operators
== for loose equality, === for strict equality, != and !== for inequality comparisons.
Relational Operators
>, <, >=, <= for numerical and alphabetical comparisons. Essential for sorting and validation.
Alternative Syntax
<> serves as alternative to != for inequality. Provides compatibility with other programming languages.
Mastering Logical Operators
Logical operators allow you to combine multiple conditions into sophisticated decision-making logic. These operators are essential for implementing complex business rules, form validation, and access control systems where multiple criteria must be evaluated simultaneously.
Return to your code editor to explore the OR operator.
Replace the if statement with this logical OR example:
$a = 3; $b = 4; if ($a == 3 || $b == 3) echo "One of these is 3.";The || operator returns true if either condition is satisfied, making it perfect for scenarios where you need flexible matching criteria.
Save and refresh to see: One of these is 3.
Now let's contrast this with the AND operator, which requires both conditions to be true:
if ($a == 3 && $b == 3) echo "Both of these equal 3.";Save and refresh—you'll see no output because both variables don't equal 3. The && operator enforces stricter requirements, useful for validation scenarios where all criteria must be met.
AND vs OR Logic
| Feature | Operator | Symbol | Required Condition |
|---|---|---|---|
| AND | && | Both conditions must be true | |
| OR | || | Either condition can be true |
Understanding Type-Strict Comparisons: == vs ===
One of PHP's most important distinctions lies in the difference between loose (==) and strict (===) equality operators. This concept is crucial for preventing subtle bugs and ensuring predictable behavior in production applications, particularly when handling user input or data from external sources like APIs or databases.
Return to your code editor for a practical type comparison demonstration.
Replace all PHP code with this type comparison example:
$a = 3; $b = '3'; if ($a == $b) echo "a equals b. "; if ($a === $b) echo "a is the same type as b.";Here we're comparing an integer (3) with a string ('3'). The == operator performs type coercion, converting values to comparable types before testing equality. The === operator, however, requires both value and type to match exactly.
Save and refresh your browser. You'll see only "a equals b." because while the values are equivalent after type conversion, they're not identical in type. This distinction becomes critical when working with form data, which arrives as strings even for numeric inputs, or when interfacing with JavaScript, which has different type coercion rules.
Close the file—we've completed our practical exploration of conditional statements.
Complete Comparison Operators Reference
| Example | Description |
|---|---|
$a == $b |
True if $a equals $b (with type conversion) |
$a != $b |
True if $a does not equal $b |
$a === $b |
True if $a equals $b and both are the same type |
$a !== $b |
True if $a does not equal $b or they are different types |
$a > $b |
True if $a is greater than $b |
$a < $b |
True if $a is less than $b |
$a <> $b |
True if $a does not equal $b (alternative syntax) |
$a <= $b |
True if $a is less than or equal to $b |
$a >= $b |
True if $a is greater than or equal to $b |
Essential Comparison Operators
Equality Operators
== for loose equality, === for strict equality, != and !== for inequality comparisons.
Relational Operators
>, <, >=, <= for numerical and alphabetical comparisons. Essential for sorting and validation.
Alternative Syntax
<> serves as alternative to != for inequality. Provides compatibility with other programming languages.
Essential Logical Operators Reference
| Example | Description |
|---|---|
$a and $b |
True if both $a and $b are true (lower precedence) |
$a or $b |
True if either $a or $b is true (lower precedence) |
$a xor $b |
True if either $a or $b is true, but not both |
!$a |
True if $a is false (negation operator) |
$a && $b |
True if both $a and $b are true (higher precedence) |
$a || $b |
True if either $a or $b is true (higher precedence) |
AND vs OR Logic
| Feature | Operator | Symbol | Required Condition |
|---|---|---|---|
| AND | && | Both conditions must be true | |
| OR | || | Either condition can be true |