PHP Fundamentals

Conditional Statements

13 min Lesson 6 of 45

Conditional Statements in PHP

Conditional statements allow your code to make decisions and execute different blocks of code based on certain conditions. They are fundamental to creating dynamic and responsive applications.

The if Statement

The if statement executes a block of code only if a specified condition is true:

<?php $age = 18; if ($age >= 18) { echo "You are an adult."; } ?>
Note: The condition inside the parentheses must evaluate to a boolean value (true or false). PHP automatically converts other types to boolean when needed.

The if...else Statement

The else clause provides an alternative block of code when the condition is false:

<?php $temperature = 25; if ($temperature > 30) { echo "It's hot outside!"; } else { echo "The weather is pleasant."; } ?>

The if...elseif...else Statement

Use elseif to test multiple conditions in sequence:

<?php $score = 75; if ($score >= 90) { echo "Grade: A"; } elseif ($score >= 80) { echo "Grade: B"; } elseif ($score >= 70) { echo "Grade: C"; } elseif ($score >= 60) { echo "Grade: D"; } else { echo "Grade: F"; } ?>
Tip: PHP evaluates conditions from top to bottom and stops at the first true condition. Order your conditions from most specific to most general.

Comparison Operators

Comparison operators are used to compare values in conditional statements:

<?php // Equal to (loose comparison) if ($a == $b) { } // Identical to (strict comparison - checks value and type) if ($a === $b) { } // Not equal to if ($a != $b) { } if ($a <> $b) { } // Not identical to if ($a !== $b) { } // Greater than if ($a > $b) { } // Less than if ($a < $b) { } // Greater than or equal to if ($a >= $b) { } // Less than or equal to if ($a <= $b) { } ?>
Warning: Use === (strict comparison) instead of == (loose comparison) to avoid unexpected type coercion. For example, 0 == "hello" is true, but 0 === "hello" is false.

Logical Operators

Logical operators allow you to combine multiple conditions:

<?php $age = 25; $hasLicense = true; // AND operator (both conditions must be true) if ($age >= 18 && $hasLicense) { echo "You can drive."; } // OR operator (at least one condition must be true) if ($age < 18 || !$hasLicense) { echo "You cannot drive."; } // NOT operator (inverts the condition) if (!$hasLicense) { echo "You need a license."; } ?>

The Ternary Operator

The ternary operator provides a shorthand way to write simple if-else statements:

<?php $age = 20; // Ternary syntax: condition ? value_if_true : value_if_false $status = ($age >= 18) ? "Adult" : "Minor"; echo $status; // Output: Adult // Traditional if-else equivalent: if ($age >= 18) { $status = "Adult"; } else { $status = "Minor"; } ?>

The Null Coalescing Operator

The null coalescing operator (??) provides a clean way to handle undefined or null values:

<?php // Returns the first value if it exists and is not null $username = $_GET['name'] ?? 'Guest'; // Equivalent to: $username = isset($_GET['name']) ? $_GET['name'] : 'Guest'; // Chaining is possible: $value = $a ?? $b ?? $c ?? 'default'; ?>
Tip: The null coalescing operator is perfect for handling optional form inputs or URL parameters safely.

The switch Statement

The switch statement is useful when you need to compare a variable against many different values:

<?php $day = "Monday"; switch ($day) { case "Monday": echo "Start of the work week"; break; case "Tuesday": case "Wednesday": case "Thursday": echo "Middle of the work week"; break; case "Friday": echo "Last day of work!"; break; case "Saturday": case "Sunday": echo "Weekend!"; break; default: echo "Invalid day"; } ?>
Warning: Always include break statements in your switch cases to prevent fall-through behavior (unless that's intentional). Without break, execution continues into the next case.

Match Expression (PHP 8.0+)

The match expression is a modern alternative to switch with stricter comparison and return values:

<?php $statusCode = 200; $message = match ($statusCode) { 200 => "OK", 404 => "Not Found", 500 => "Server Error", default => "Unknown Status" }; echo $message; // Output: OK ?>
Note: Unlike switch, match uses strict comparison (===) and doesn't require break statements. It also returns a value directly.

Truthy and Falsy Values

In PHP, certain values are considered "falsy" (evaluate to false) in conditional statements:

<?php // Falsy values: if (false) { } // boolean false if (0) { } // integer zero if (0.0) { } // float zero if ("") { } // empty string if ("0") { } // string "0" if (null) { } // null if ([]) { } // empty array // Everything else is truthy: if (true) { } // boolean true if (1) { } // non-zero numbers if ("hello") { } // non-empty strings if ([1, 2]) { } // non-empty arrays ?>

Practice Exercise

Task: Create a login validation system:

  1. Define variables for username and password
  2. Check if username is "admin" AND password is "secret123"
  3. If both correct, display "Welcome Admin!"
  4. If username correct but password wrong, display "Invalid password"
  5. Otherwise, display "Invalid credentials"
  6. Bonus: Use a variable to track login attempts and lock after 3 failed attempts

Best Practices

  • Use strict comparison (===) to avoid type coercion issues
  • Keep conditions simple and readable - extract complex logic into variables
  • Use early returns to reduce nesting: if (!$valid) return;
  • Prefer match over switch in PHP 8+ for cleaner code
  • Use the null coalescing operator for default values
  • Avoid deeply nested if statements - consider refactoring into functions

ES
Edrees Salih
12 hours ago

We are still cooking the magic in the way!