Operators perform operations on variables and values. PHP includes arithmetic, assignment, comparison, logical, bitwise, string concatenation, and modern operators like Null Coalescing (??) and Spaceship (<=>).
+, -, *, /, % (Modulo), ** (Exponentiation)==, === (Strict), !=, !==, <, >, <=, >=, <=> (Spaceship)&& (AND), || (OR), ! (NOT)=, +=, -=, *=, /=, .=$val ?? $default (Returns $val if set and not null, otherwise $default)<=>) & Null Coalescing (??)flowchart TD
A["Evaluation Operator"] --> B{"Choose Operator"}
B -- Spaceship ($a <=> $b) --> C["Returns -1 if $a < $b, 0 if $a == $b, 1 if $a > $b"]
B -- Null Coalescing ($a ?? $b) --> D["Returns $a if set and non-null, else $b"]
B -- Strict Equality ($a === $b) --> E["Compares both value and type"]
<?php
declare(strict_types=1);
// 1. Strict vs Loose Comparison
$ageString = "25";
$ageInt = 25;
echo "Loose Equality (==): " . ($ageString == $ageInt ? "True" : "False") . "
"; // True
echo "Strict Equality (===): " . ($ageString === $ageInt ? "True" : "False") . "
"; // False
// 2. Spaceship Operator (<=>) for Sorting Arrays
$numbers = [10, 5, 20, 15];
usort($numbers, fn($a, $b) => $a <=> $b); // Ascending sort: [5, 10, 15, 20]
echo "Sorted Numbers: " . implode(", ", $numbers) . "
";
// 3. Null Coalescing Operator (??) & Assignment (??=)
$requestData = ['username' => 'maksudur'];
$currentUser = $requestData['username'] ?? 'Guest';
$theme = $requestData['theme'] ??= 'dark_mode'; // Assigns 'dark_mode' if 'theme' is unset
echo "Current User: $currentUser | Selected Theme: $theme
";
=== and !==: Prevents unexpected bugs caused by implicit PHP loose type coercions (e.g. "0" == false evaluates to true!).?? over isset() Ternary: Use $val ?? 'default' instead of isset($val) ? $val : 'default'.<=> in Callback Comparison Functions: Simplifies custom array sorting callbacks in usort().Write a line of code using the null coalescing operator ?? that assigns $userRole to $_GET['role'] if it exists, or 'subscriber' if it is missing or null!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.