Operators

Course 1 · Ch 3
Operators and Control Structures
Comparison and logical operators, if/elseif/else, and switch — the constructs that let a script make decisions

Chapter 2 covered comparing values with == and ===. This chapter covers the full range of operators PHP offers, and the control structures that actually use them to change what a script does based on those comparisons.

Comparison Operators

OperatorMeaning
==Equal (loose, juggles types — Chapter 2)
===Identical (strict, no juggling)
!= / <>Not equal (loose)
!==Not identical (strict)
> / < / >= / <=Greater than, less than, and their "or equal" variants
<=>Spaceship operator — returns -1, 0, or 1 for less/equal/greater, genuinely useful in custom sorting

Logical Operators

<?php $age = 25; $hasLicense = true; var_dump($age >= 18 && $hasLicense); // true — both conditions must be true var_dump($age < 18 || $hasLicense); // true — at least one condition is true var_dump(!$hasLicense); // false — negates the value ?>

&& (AND), || (OR), and ! (NOT) combine and negate boolean expressions — the building blocks behind any condition more complex than a single comparison.

if / elseif / else

<?php $score = 75; if ($score >= 90) { echo "Grade: A"; } elseif ($score >= 70) { echo "Grade: B"; } elseif ($score >= 50) { echo "Grade: C"; } else { echo "Grade: F"; } ?>

PHP checks each condition in order, top to bottom, and runs the block belonging to the first one that evaluates to true — every subsequent elseif/else is skipped entirely once a match is found, even if a later condition would also have been true.

elseif is one word in PHP — else if (two words) also works, but means something subtly different
elseif and else if behave identically in almost every practical case, but technically else if is actually an else block containing a nested if statement — relevant specifically when using PHP's alternative colon syntax (covered in templates), where only the single-word elseif is valid. Sticking with elseif consistently avoids needing to remember this distinction at all.

The Ternary Operator — A Compact if/else

<?php $age = 20; $status = ($age >= 18) ? "adult" : "minor"; echo $status; // "adult" // The null coalescing operator — a common, related shorthand $username = $_GET['user'] ?? 'Guest'; // use 'Guest' if $_GET['user'] isn't set ?>

The ternary operator condenses a simple if/else assignment into one line. The null coalescing operator (??) is a closely related, extremely common shorthand specifically for "use this value, or a fallback if it doesn't exist/is null" — genuinely useful and previewed here ahead of full coverage when $_GET/$_POST are properly introduced in Chapter 8.

switch — Comparing One Value Against Several Options

<?php $day = "Wednesday"; switch ($day) { case "Monday": echo "Start of the week"; break; case "Wednesday": echo "Midweek"; break; case "Friday": echo "Almost the weekend"; break; default: echo "Just another day"; } ?>
Forgetting break is one of the most common switch mistakes — execution "falls through" to the next case
Without a break, PHP continues executing every subsequent case's code, regardless of whether its own condition matched — this "fall-through" behaviour is occasionally used deliberately (multiple case labels sharing one block of code), but is far more often an accidental bug when a break is simply forgotten on a case that genuinely needed one.

When switch Is Better Than a Long elseif Chain

Both accomplish the same thing for comparing one variable against many possible exact values — switch is generally considered more readable once there are more than roughly 3-4 options, since it avoids repeating the variable name and comparison operator in every single condition.

Coding Challenges

Challenge 1

Write an if/elseif/else chain that takes a temperature in Celsius (use a variable, try a few different values) and echoes "Freezing", "Cold", "Mild", or "Hot" based on reasonable thresholds you choose yourself.

📄 View solution
Challenge 2

Using the ternary operator, write a single line that assigns "Pass" or "Fail" to a variable based on whether a score variable is 50 or above. Then write the equivalent using a full if/else block, and compare the two.

📄 View solution
Challenge 3

Write a switch statement that takes a variable holding a month number (1-12) and echoes the correct season ("Winter", "Spring", "Summer", "Autumn") — group multiple case labels together for months sharing a season, using fall-through deliberately.

📄 View solution

Chapter 3 Quick Reference

  • Comparison operators: ==/===, !=/!==, >/</>=/<=, <=> (spaceship)
  • Logical operators: && (AND), || (OR), ! (NOT)
  • if/elseif/else — runs the FIRST matching block only, top to bottom, skipping the rest
  • Ternary (cond ? a : b) — compact if/else for simple assignments
  • ?? (null coalescing) — value, or a fallback if it's null/unset; previewed here, full coverage in Chapter 8
  • switch/case/break/default — compares one value against several exact options
  • Forgetting break causes fall-through — occasionally deliberate, more often an accidental bug
  • Next chapter: loops — for, while, foreach