PHP Tutorial · PHP Basics · Lesson 12 of 38

PHP Operators

Arithmetic, comparison, logical, null coalescing and the spaceship operator.

Arithmetic and assignment

+ - * / % ** and their assignment forms += -= *= /= .= ??=.

Comparison

Operator Meaning
== equal after type juggling
=== identical: same value and type
!= / !== not equal / not identical
<=> spaceship: returns -1, 0 or 1

Prefer === — loose == comparisons are a classic source of bugs.

Example 1Try it yourself
<?php
var_dump(5 == "5", 5 === "5");
var_dump(0 == "a");          // false in PHP 8 (true in PHP 7!)
var_dump(null == false, null === false);
echo 1 <=> 2, " ", 2 <=> 2, " ", 3 <=> 2, "\n";

Output

bool(true)
bool(false)
bool(false)
bool(true)
bool(false)
-1 0 1

Logical operators

&&, || and ! (also and, or, xor with lower precedence — avoid those).

Null coalescing

$a ?? $b returns $a if it exists and isn't null, otherwise $b — ideal for reading optional input. ??= assigns only when the variable is null. The nullsafe operator ?-> stops a method chain when a value is null.

Example 2Try it yourself
<?php
$query = ["page" => "3"];
$page = $query["page"] ?? 1;
$sort = $query["sort"] ?? "newest";
echo "page=$page sort=$sort\n";
$config = [];
$config["theme"] ??= "light";
echo $config["theme"], "\n";
$user = null;
var_dump($user?->getName());

Output

page=3 sort=newest
light
NULL

Test yourself

What does 2 <=> 5 return?

  1. -1
  2. 0
  3. 1
  4. false
Show answer

Answer: -1

Practice next