Operators in PHP
Explore PHP arithmetic, comparison, logical, string, bitwise, and assignment operators with runnable Docker examples.
Operators are the verbs of a programming language — they transform values, compare them, and combine them into expressions. PHP inherits much of its operator syntax from C and Perl, but layers on a few quirks of its own: a dedicated string concatenation operator, two flavors of equality (loose and strict), and modern additions like the null coalescing (??) and spaceship (<=>) operators.
Because PHP is dynamically and weakly typed, operators often perform implicit conversions between strings, integers, floats, and booleans. PHP 8 tightened many of these rules — particularly comparisons between numbers and non-numeric strings — so the language now behaves much more predictably than its earlier reputation suggests. Understanding which operator triggers which conversion is the key to writing PHP that does what you mean.
This tutorial walks through every major operator category in PHP, with a single runnable example you can execute in Docker. Along the way, we’ll highlight the operators that distinguish PHP from C-family languages: . for concatenation, ?? for null fallback, <=> for three-way comparison, and the difference between == and ===.
A Tour of PHP Operators
The program below exercises arithmetic, string, comparison, logical, assignment, and bitwise operators in turn. Each section prints labeled output so you can match every expression to its result.
Create a file named operators.php:
| |
What’s happening here
.and.=— PHP uses the dot for string concatenation, because+is reserved for numeric addition.$msg .= " Welcome."appends in place.**— Exponentiation.17 ** 5evaluates to1419857.intdiv($a, $b)— Integer division./always returns a float when the result isn’t a whole number; useintdiv(or cast) when you need a truncated integer.==vs===— Loose equality (==) allows type juggling; strict equality (===) requires both type and value to match. Since PHP 8, comparing a number to a non-numeric string converts the number to a string rather than the other way around, so0 == ""is nowfalse.<=>— The spaceship operator returns-1,0, or1. It is most useful inusort()callbacks.??vs?:— Null coalescing returns the right side only when the left isnullor undefined. The Elvis operator (?:) returns the right side for any falsy value (false,0,"",null,[]).
Running with Docker
| |
Expected Output
Arithmetic (17, 5):
a + b = 22
a - b = 12
a * b = 85
a / b = 3.4
a % b = 2
intdiv = 3
a ** b = 1419857
String operators:
concat (.) : Hello, PHP!
append(.=) : Hello, PHP! Welcome.
Comparison (loose vs strict):
0 == "0" : true
0 == "" : false
"1" == 1 : true
"1" === 1 : false
1 <=> 2 : -1
2 <=> 2 : 0
3 <=> 2 : 1
Logical:
t && f : false
t || f : true
!t : false
t xor f : true
Null coalescing and ternary:
mode (??) : production
short (?:) : default
status (?:) : adult
Assignment shortcuts (start n = 10):
n += 5 -> 15
n -= 3 -> 12
n *= 2 -> 24
n /= 4 -> 6
n **= 2 -> 36
n %= 7 -> 1
Bitwise (5 = 0b0101, 3 = 0b0011):
5 & 3 = 1
5 | 3 = 7
5 ^ 3 = 6
~5 = -6
5 << 2 = 20
20 >> 1 = 10
Operator Precedence
PHP evaluates operators in a defined precedence order, similar to most C-family languages. A few highlights:
**(right-associative) — exponentiation binds tightest among arithmetic ops.*,/,%— multiplication, division, modulus.+,-— addition and subtraction..— string concatenation (lowered below+/-in PHP 8).<,<=,>,>=— relational comparisons.==,!=,===,!==,<=>— equality.&&,||— short-circuit logical operators (higher precedence thanand,or).? :,??— ternary and null coalescing.=,+=,-=, etc. — assignment is near the bottom.
A subtle gotcha: and/or/xor exist as alternatives to &&/||/xor, but they have lower precedence than =, which means $x = true and false assigns true to $x and then evaluates and false separately. Prefer && and || unless you have a specific reason otherwise.
Create a file named precedence.php:
| |
Run it the same way:
| |
Expected Output
2 ** 3 ** 2 = 512
1 + 2 . '+' . 3 + 4 = 3+7
x = false
y = true
The 1 + 2 . '+' . 3 + 4 result is "3+7" because — as of PHP 8 — the . operator has lower precedence than + and -. The arithmetic groups first: (1 + 2) . '+' . (3 + 4), producing "3" . "+" . "7", which concatenates to "3+7". (Rewrite expressions like this with explicit parentheses regardless — clarity beats relying on memorized precedence.)
Key Concepts
- String concatenation uses
.— PHP reserves+for numeric addition; mixing strings and+either fails or coerces unexpectedly. - Two equalities — Use
===and!==by default; reserve==for cases where type juggling is genuinely what you want. - The spaceship operator (
<=>) returns-1,0, or1and is purpose-built for comparator callbacks likeusort(). ??falls back onnull;?:falls back on any falsy value. They are not interchangeable.- PHP 8 fixed loose comparison surprises — Comparing a number to a non-numeric string no longer silently coerces the string to
0. /always returns a float when results aren’t whole. Useintdiv()for integer division.**is right-associative —2 ** 3 ** 2is2 ** 9, not8 ** 2.- Prefer
&&/||overand/or— The lower-precedence keyword forms interact badly with assignment.
Running Today
All examples can be run using Docker:
docker pull php:8.4-cli-alpine
Comments
Loading comments...
Leave a Comment