PHP Operators

PHP operators let you calculate, compare and combine values. Most look familiar from math, but a few, like === and ??, are especially important in PHP because of its automatic type conversion.

Arithmetic and Assignment Operators

<?php
$a = 17; $b = 5;
echo $a + $b, " ", $a - $b, " ", $a * $b, "\n";
echo $a / $b, " ", $a % $b, " ", $a ** 2, "\n";
echo intdiv($a, $b), "\n";
$a += 3;
echo $a;
22 12 85
3.4 2 289
3
20

Comparison: == vs ===

The == operator compares values after type juggling, while === also requires the same type. Prefer === to avoid surprises.

  • <=> (spaceship) returns -1, 0 or 1 and is handy for sorting
  • Since PHP 8, 0 == "a" is false, which fixed an old trap
<?php
var_dump(5 == "5");
var_dump(5 === "5");
var_dump(0 == "a");
var_dump(null == false);
var_dump(5 != 6, 5 <=> 6);
bool(true)
bool(false)
bool(false)
bool(true)
bool(true)
int(-1)

Logical Operators

  • && (and): true if both sides are true
  • || (or): true if at least one side is true
  • ! (not): flips true and false
  • xor: true if exactly one side is true
  • Prefer && and || over and/or, which have lower precedence

Ternary and Null Coalescing Operators

The ternary operator picks one of two values. The null coalescing operator ?? returns the left side unless it is null or undefined, which is perfect for reading optional input.

<?php
$age = 20;
echo $age >= 18 ? "adult" : "minor", "\n";

$params = ['page' => 3];
$page = $params['page'] ?? 1;
$sort = $params['sort'] ?? 'newest';
echo "$page $sort\n";

$user = null;
$user ??= 'guest';
echo $user;
adult
3 newest
guest

Increment and String Operators

$i++ returns the old value then increments; ++$i increments first. The dot joins strings.

<?php
$i = 5;
echo $i++, " ", $i, " ", ++$i, "\n";
$greeting = "Good" . " " . "morning";
echo $greeting;
5 6 7
Good morning

Frequently asked questions

What is the difference between == and === in PHP?

== compares values after converting types, while === requires both the value and the type to be equal. Using === is safer.

What does ?? mean in PHP?

It is the null coalescing operator. $x ?? $default returns $x if it exists and is not null, otherwise $default, without a warning.

What is the spaceship operator used for?

<=> compares two values and returns -1, 0 or 1. It is mainly used in usort callbacks to sort arrays.