PHP Operators (Full Guide)
Operators let you compute values, compare, make decisions, concatenate strings, merge arrays, and more. This page is a complete reference with examples and common pitfalls.
1) Arithmetic Operators
| Operator | Meaning | Example |
|---|---|---|
+ | Addition | $a + $b |
- | Subtraction | $a - $b |
* | Multiplication | $a * $b |
/ | Division | $a / $b |
% | Modulo (remainder) | $a % $b |
** | Exponentiation | $a ** $b (e.g., 2**3 = 8) |
<?php
$a = 10; $b = 3;
echo "Add: " . ($a+$b) . "\n";
echo "Pow: " . ($a**$b);
?>
Note: Division of integers can produce a float (e.g.,
5/2 = 2.5).2) Assignment Operators
| Operator | Meaning | Example |
|---|---|---|
= | Assign | $x = 5; |
+=, -=, *=, /=, %=, **= | Compound assignment | $x += 3; |
.= | Concatenate and assign | $s .= " world"; |
&=, |=, ^=, <<=, >>= | Bitwise compound | $n <<= 1; |
Assignment by Reference (&)
<?php
$a = 10;
$b =& $a; // $b references $a
$b = 20;
echo $a; // 20
?>
Be careful: References can surprise you when passing variables into functions. Use sparingly.
3) Increment / Decrement
| Form | Effect | Returns |
|---|---|---|
++$x | Pre-increment | Increments, then returns new value |
$x++ | Post-increment | Returns original value, then increments |
--$x | Pre-decrement | Decrements, then returns new value |
$x-- | Post-decrement | Returns original value, then decrements |
4) Comparison Operators
| Operator | Meaning | Example / Result |
|---|---|---|
== | Equal (type juggling) | "5" == 5 → true |
=== | Identical (value & type) | "5" === 5 → false |
!=, <> | Not equal | 3 != "3" → false |
!== | Not identical | 3 !== "3" → true |
<, >, <=, >= | Relational | 2 < 3 → true |
<=> | Spaceship | Returns -1, 0, 1 for <, =, > |
?? | Null coalescing | First defined/nonnull value |
Type Juggling Pitfalls (== vs ===)
<?php
var_dump("0" == 0); // true (juggled)
var_dump("0" === 0); // false (type differs)
var_dump("" == 0); // true (!)
var_dump("0" == false); // true
// Prefer === and !== for safety
?>
Spaceship (<=>)
<?php
// -1 if left < right, 0 if equal, 1 if left > right
echo 2 <=> 3; // -1
echo 3 <=> 3; // 0
echo 4 <=> 3; // 1
?>
Null Coalescing (??)
Returns the first operand that exists and isn’t NULL.
<?php
$name = $_GET['name'] ?? 'Guest';
echo "Hello, $name";
?>
5) Logical Operators
| Operator | Meaning | Truth Table (A op B) |
|---|---|---|
&&, and | Logical AND | TT→T, TF→F, FT→F, FF→F |
||, or | Logical OR | TT→T, TF→T, FT→T, FF→F |
xor | Exclusive OR | TT→F, TF→T, FT→T, FF→F |
! | NOT | !T→F, !F→T |
Precedence trap:
&&/|| have higher precedence than and/or. Use parentheses if unsure.<?php
$a = true or false; // ($a = true) or false → $a is true
$b = true || false; // $b = (true || false) → $b is true
?>
6) Ternary & Elvis
| Form | Meaning | Example |
|---|---|---|
cond ? A : B | If cond true → A else B | $msg = $ok ? "Yes" : "No"; |
A ?: B | Elvis (if A truthy → A else B) | $user = $name ?: "Guest"; |
Tip: Use
?? when you specifically want “first defined & not null” (not just truthy).7) String Operators
| Operator | Meaning | Example |
|---|---|---|
. | Concatenation | $s = "Hello" . " World"; |
.= | Append to string | $s .= "!" |
8) Array Operators
| Operator | Meaning | Notes |
|---|---|---|
+ | Union | Keeps keys from the left operand if duplicate |
==, === | Equality / Identity | === also compares types and order |
!=, <>, !== | Inequality / Non-identity | — |
<?php
$a = ["id"=>1, "name"=>"A"];
$b = ["name"=>"B", "age"=>20];
$u = $a + $b; // ["id"=>1, "name"=>"A", "age"=>20]
var_dump($u);
?>
Note: For combining arrays by values (reindexing), use
array_merge(). For keys, consider $a + $b depending on desired behavior.9) Bitwise Operators
| Operator | Meaning | Example |
|---|---|---|
& | AND | 6 & 3 = 2 (110 & 011 → 010) |
| | OR | 6 | 3 = 7 |
^ | XOR | 6 ^ 3 = 5 |
~ | NOT | ~6 |
<< | Left shift | 3 << 1 = 6 |
>> | Right shift | 6 >> 1 = 3 |
Use cases: flags/permissions, low-level protocols, compact booleans.
10) Error Suppression (@)
Prefixing an expression with @ hides error messages from that expression.
<?php
// not recommended: hides useful errors
$f = @file_get_contents("missing.txt");
?>
Avoid: Better to handle errors properly or adjust
error_reporting in php.ini during development.11) instanceof & Nullsafe ?-> (PHP 8)
instanceof checks object type; nullsafe operator avoids errors when a chain is null.
<?php
class User { public $profile; }
$u = new User();
var_dump($u instanceof User);
$city = $u->profile?->address?->city ?? "Unknown";
?>
12) Execution Operator (Backticks)
Backticks `cmd` execute a shell command and return output (same as shell_exec()).
Security: Never use with unsanitized input. Avoid in web apps unless you fully understand risks.
13) Operator Precedence & Associativity (Essential)
| Higher → Lower | Notes |
|---|---|
| Clone/new | object creation |
** | right-associative |
++, --, ~, ! , (type), @ | unary |
* / % | — |
+ - . | . concatenation |
<< >> | shifts |
Relational: < > <= >= | — |
Equality: == != === !== <=> | — |
& (bitwise AND) | — |
^ (bitwise XOR) | — |
| (bitwise OR) | — |
&& | logical AND |
|| | logical OR |
?? | null coalescing |
? : | ternary |
=, compound assigns | right-associative |
and, xor, or | lowest among logicals |
Rule of thumb: When readability matters, add parentheses — especially with mixed
., +, and logicals.Practice Tasks
- Use
<=>to sort an array of associative users byage, then byname. - Given
$_GET['page'], safely compute$pageas an integer defaulting to 1 using??and casting. - Demonstrate the difference between
andvs&&in an assignment expression. - Merge two arrays with the
+operator and witharray_merge(); explain the difference in keys. - Build a permission flags integer using bitwise operators, and test for a flag with
&.
Next: Move to Conditional Statements (if/elseif/else, switch, match (PHP 8), patterns).