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

OperatorMeaningExample
+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

OperatorMeaningExample
=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

FormEffectReturns
++$xPre-incrementIncrements, then returns new value
$x++Post-incrementReturns original value, then increments
--$xPre-decrementDecrements, then returns new value
$x--Post-decrementReturns original value, then decrements

4) Comparison Operators

OperatorMeaningExample / Result
==Equal (type juggling)"5" == 5 → true
===Identical (value & type)"5" === 5 → false
!=, <>Not equal3 != "3" → false
!==Not identical3 !== "3" → true
<, >, <=, >=Relational2 < 3 → true
<=>SpaceshipReturns -1, 0, 1 for <, =, >
??Null coalescingFirst 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

OperatorMeaningTruth Table (A op B)
&&, andLogical AND TT→T, TF→F, FT→F, FF→F
||, orLogical OR TT→T, TF→T, FT→T, FF→F
xorExclusive 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

FormMeaningExample
cond ? A : BIf cond true → A else B$msg = $ok ? "Yes" : "No";
A ?: BElvis (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

OperatorMeaningExample
.Concatenation$s = "Hello" . " World";
.=Append to string$s .= "!"

8) Array Operators

OperatorMeaningNotes
+UnionKeeps 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

OperatorMeaningExample
&AND6 & 3 = 2 (110 & 011 → 010)
|OR6 | 3 = 7
^XOR6 ^ 3 = 5
~NOT~6
<<Left shift3 << 1 = 6
>>Right shift6 >> 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 → LowerNotes
Clone/newobject creation
**right-associative
++, --, ~, ! , (type), @unary
* / %
+ - .. concatenation
<< >>shifts
Relational: < > <= >=
Equality: == != === !== <=>
& (bitwise AND)
^ (bitwise XOR)
| (bitwise OR)
&&logical AND
||logical OR
??null coalescing
? :ternary
=, compound assignsright-associative
and, xor, orlowest among logicals
Rule of thumb: When readability matters, add parentheses — especially with mixed ., +, and logicals.

Practice Tasks

  1. Use <=> to sort an array of associative users by age, then by name.
  2. Given $_GET['page'], safely compute $page as an integer defaulting to 1 using ?? and casting.
  3. Demonstrate the difference between and vs && in an assignment expression.
  4. Merge two arrays with the + operator and with array_merge(); explain the difference in keys.
  5. 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).