Tutorials › PHP Tutorial › PHP Operators

PHP Operators

14 min read · Lesson 10 of 24

Operators are symbols that do something with values: add them, compare them, combine conditions or join text. PHP groups them into families. You will use almost all of these every day.

Arithmetic operators

OperatorNameExampleResult
+addition10 + 313
-subtraction10 - 37
*multiplication10 * 330
/division10 / 42.5
%modulus (remainder)10 % 31
**exponent (power)10 ** 31000
Example PHP
<?php
$total = 2450;
$people = 4;
echo "Each pays: " . $total / $people . "\n";
echo "Left over shillings: " . $total % $people . "\n";
echo "Is 17 even? " . (17 % 2 === 0 ? "yes" : "no") . "\n";
Result
Each pays: 612.5
Left over shillings: 2
Is 17 even? no
Open in editor

The modulus % is perfect for checking whether a number is even ($n % 2 === 0) or for doing something every *n*th time in a loop.

Assignment operators

= stores a value. The combined forms do a calculation and store the result in one step.

OperatorSame as
$x += 5$x = $x + 5
$x -= 5$x = $x - 5
$x *= 5$x = $x * 5
$x /= 5$x = $x / 5
$x %= 5$x = $x % 5
$x .= "a"$x = $x . "a"
$x ??= 5$x = $x ?? 5
Example PHP
<?php
$balance = 1000;
$balance += 500;    // deposit
$balance -= 200;    // withdrawal
$balance *= 2;
echo $balance;
Result
2600
Open in editor

Increment and decrement

OperatorMeaning
++$xadd 1, then return the new value
$x++return the current value, then add 1
--$xsubtract 1, then return the new value
$x--return the current value, then subtract 1
Example PHP
<?php
$a = 5;
echo $a++ . "\n";   // prints 5, then $a becomes 6
echo $a . "\n";
echo ++$a . "\n";   // $a becomes 7, then prints 7
Result
5
6
7
Open in editor

Comparison operators

Comparisons give a boolean (true or false).

OperatorNameTrue when...
==equalvalues are equal after type juggling
===identicalvalues are equal and of the same type
!= or <>not equalvalues differ after type juggling
!==not identicalvalue or type differs
<, >, <=, >=less/greater thanas in maths
<=>spaceshipreturns -1, 0 or 1
Example PHP
<?php
var_dump(5 == "5");
var_dump(5 === "5");
var_dump(5 !== "5");
var_dump(0 == "");
var_dump(null == false);
echo (3 <=> 7) . " " . (7 <=> 7) . " " . (9 <=> 7);
Result
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
-1 0 1
Open in editor
Tip: Use === and !== by default. Loose comparison (==) converts types first, which leads to surprising results such as null == false being true. Strict comparison avoids a whole class of bugs.

The spaceship operator <=> is mainly used when sorting (see Array Functions).

Logical operators

Logical operators combine conditions.

  • && (or the word and): true when both sides are true.
  • || (or the word or): true when at least one side is true.
  • ! (not): flips true to false and false to true.
  • xor (exclusive or): true when exactly one side is true.
Example PHP
<?php
$age = 20;
$hasId = true;
$isMember = false;

var_dump($age >= 18 && $hasId);
var_dump($isMember || $age > 65);
var_dump(!$isMember);
Result
bool(true)
bool(false)
bool(true)
Open in editor
Warning: and and or have lower priority than =. So $ok = true and false; sets $ok to true! Always use && and || unless you know exactly why you need the word forms.

PHP stops evaluating as soon as the answer is known ("short-circuit"). In $user && $user->isAdmin(), the method is never called if $user is empty.

String operators

There are only two: . joins strings, and .= appends to a string. See Strings.

The ternary operator

condition ? valueIfTrue : valueIfFalse is a short if/else that produces a value.

Example PHP
<?php
$marks = 48;
$result = $marks >= 50 ? "Pass" : "Fail";
echo $result . "\n";

$items = 1;
echo "You have $items item" . ($items === 1 ? "" : "s") . "\n";
Result
Fail
You have 1 item
Open in editor

Null coalescing operator ??

$a ?? $b returns $a if it exists and is not null, otherwise $b. It never raises an "undefined" warning, which makes it ideal for optional form fields and settings.

Example PHP
<?php
$settings = ["theme" => "dark"];

$theme = $settings["theme"] ?? "light";
$lang = $settings["lang"] ?? "en";
echo "$theme / $lang\n";

$nickname = null;
echo $nickname ?? "Guest";
Result
dark / en
Guest
Open in editor

Operator precedence

When an expression has several operators, PHP follows rules similar to school maths: ** first, then *, /, %, then +, -, then comparisons, then &&, then ||, then assignment. Use brackets to make your intent clear.

Example PHP
<?php
echo 2 + 3 * 4 . "\n";
echo (2 + 3) * 4 . "\n";
echo -2 ** 2 . "\n";
Result
14
20
-4
Open in editor

The last line shows that ** binds tighter than the minus sign, so it is calculated as -(2 ** 2).

Exercise

Use the operator that checks value AND type.

if ($input  "yes") { echo "OK"; }
Exercise

Give $name a default of "Guest" if $_GET["name"] is missing.

$name = $_GET["name"]  "Guest";
Exercise

Add 100 to $points using a combined assignment operator.

$points  100;
Sign in or create a free account to track progress, earn XP, badges and a certificate.