Conditionals (if-else & switch)

🐘 PHP Lesson 4 Beginner

Conditionals control the branch paths of execution based on boolean checks. In this lesson, we will look at if-else blocks, ternary operators, and PHP's null coalescing operator (??).

1 Null Coalescing (??) & Alternative HTML colon syntax

PHP conditionals support modern operators and styling alternatives:

  • Null Coalescing Operator (`??`): Returns its first operand if it exists and is not null; otherwise, returns the second operand. Highly useful for managing fallback values: `$name = $_GET['user'] ?? 'Guest';`.
  • Alternative Syntax (`if:` / `endif;`): In pure PHP files embedded within HTML pages, PHP provides colon-based blocks to make layout nesting cleaner and easier to read.
2 Conditionals Code

Let's run a program evaluating conditions and checking null coalescing operators:

PHP — Conditionals ▶ Run Code
<?php
$score = 85;

if ($score >= 90) {
    echo "Grade: A\n";
} elseif ($score >= 80) { // Note that 'elseif' is a single word in PHP
    echo "Grade: B\n";
} else {
    echo "Grade: F\n";
}

// Null Coalescing Operator fallback check
$username = null;
$displayName = $username ?? "Guest User";
echo "Welcome, " . $displayName . "\n";
?>
3 Code Challenge
Challenge: Write a nested conditional checking if a user has admin access. Expose a boolean flag `$logged_in` and a string `$role`. Display "Access Granted" if both checks are satisfied.