What an operator is
An operator takes one or more values and produces a new value. You have already used several: = to assign, + to add, . to join strings. This lesson collects the ones you will use every day and the rules for combining them.
Assignment and compound assignment
= stores a value. Compound assignment operators combine a calculation with the assignment, which keeps code short when a variable is updated in place:
<?php
$balance = 100;
$balance += 50; // same as $balance = $balance + 50
$balance -= 30;
$balance *= 2;
$balance /= 4;
echo $balance . "\n";
$message = "Order";
$message .= " shipped";
echo $message . "\n";
$count = null;
$count ??= 0; // assign only if null or unset
echo $count . "\n";60
Order shipped
0??= assigns only when the variable is null or does not exist, which is handy for defaults. It belongs to the null coalescing family covered in its own lesson.
Increment and decrement
++ adds one and -- subtracts one. The position matters when the expression's value is used at the same time:
<?php
$i = 5;
echo $i++ . "\n"; // prints 5, then $i becomes 6
echo $i . "\n";
echo ++$i . "\n"; // $i becomes 7 first, then prints 7
echo $i-- . "\n";
echo $i . "\n";5
6
7
7
6$i++ (post-increment) gives the old value, then increases the variable. ++$i (pre-increment) increases first. When the increment stands alone on a line, as in a loop counter, the two are identical. To avoid surprises, do not use ++ inside a larger expression.
Comparison operators
Comparisons produce a boolean, true or false:
| Operator | True when |
|---|---|
== |
values are equal after type conversion |
=== |
values are equal and of the same type |
!= or <> |
not equal (after conversion) |
!== |
not identical |
<, <=, >, >= |
less than, at most, greater than, at least |
<?php
var_dump(10 > 5);
var_dump(10 <= 9);
var_dump("10" == 10);
var_dump("10" === 10);bool(true)
bool(false)
bool(true)
bool(false)The difference between == and === is important enough for a lesson of its own. The short version: use === unless you have a reason not to.
The spaceship operator
<=> compares two values and returns -1 if the left is smaller, 0 if they are equal and 1 if the left is larger. It exists to make sorting functions short:
<?php
echo (3 <=> 7) . "\n";
echo (7 <=> 7) . "\n";
echo ("pear" <=> "apple") . "\n";
$prices = [24.99, 9.5, 89.5];
usort($prices, fn($a, $b) => $a <=> $b);
echo implode(", ", $prices) . "\n";-1
0
1
9.5, 24.99, 89.5You will use it constantly in Sorting arrays.
Logical operators
Logical operators combine booleans:
| Operator | Meaning |
|---|---|
&& |
and: true if both sides are true |
|| |
or: true if at least one side is true |
! |
not: flips true and false |
xor |
true if exactly one side is true |
<?php
$age = 25;
$hasTicket = true;
var_dump($age >= 18 && $hasTicket);
var_dump($age < 12 || $age > 60);
var_dump(!$hasTicket);bool(true)
bool(false)
bool(false)&& and || short-circuit: they stop as soon as the answer is certain. In $user !== null && $user->isAdmin(), the method is only called when $user is not null, which is exactly what you want.
PHP also has the words and and or. They mean the same thing but have lower precedence than =, which produces a famous bug:
<?php
$ok = true and false;
var_dump($ok);
$ok = true && false;
var_dump($ok);bool(true)
bool(false)In the first line PHP does ($ok = true) and false. Stick to && and ||.
Precedence
When an expression mixes operators, precedence decides which runs first, much like multiplication before addition in maths. Roughly, from first to last: **, then ++ -- ! and casts, then * / %, then + -, then ., then comparisons, then &&, then ||, then ??, then the ternary ? :, then assignment.
<?php
echo 2 + 3 * 4 . "\n";
echo (2 + 3) * 4 . "\n";
echo -2 ** 2 . "\n";14
20
-4-2 ** 2 is -(2 ** 2), because ** binds more tightly than the minus sign. Nobody remembers the whole table. Add brackets whenever there is any doubt; they cost nothing and make the intention clear.
Common mistakes
- Using = when you mean == or === in a condition.
if ($status = 'paid')assigns and is always true. - Using and/or instead of &&/|| next to an assignment.
- Relying on precedence you are unsure of. Add brackets.
- Using ++ inside a longer expression, where pre and post forms give different results.
Exercise
A cart total is 1,250. Apply a 10% discount with *=, then add 49 shipping with +=. Finally print whether the customer qualifies for a gift: total above 1,000 and a member, where $isMember = false.
Show one possible answer
<?php
$total = 1250;
$isMember = false;
$total *= 0.9;
$total += 49;
echo "Total: $total\n";
var_dump($total > 1000 && $isMember);Total: 1174
bool(false)Key points
- Compound assignment operators such as +=, -=, *= and .= update a variable in place.
- ++$i increments before the value is used, $i++ after. Both add one.
- && and || stop as soon as the answer is known (short-circuit). and and or work the same but bind more weakly than =, which causes bugs.
- The spaceship operator <=> returns -1, 0 or 1 and is made for sorting.