Learning Objectives – after this chapter you will be able to:
- Use arithmetic, assignment, comparison, logical, increment/decrement and string operators.
- Tell the difference between
==and===. - Use combined operators such as
+=and.=. - Apply operator precedence and associativity, and override them with parentheses.
- Use the modern operators
??,<=>and**.
Expressions and Operators
In PHP there are two kinds of "expressions" you will hear about. One is the regular expression, used to manipulate text (Chapter 12). The other is more mathematical – it describes operations to be performed on values and variables:
$c = $a + $b;
Assuming $a and $b are numbers, this expression adds them and stores the sum in $c (the = sign makes it an assignment). In $a + $b the plus sign is an arithmetic operator; $a and $b are its operands.
Arithmetic Operators
| Operator | Symbol | Example | Result ($a = 17, $b = 5) |
|---|---|---|---|
| Addition | + | $a + $b | 22 |
| Subtraction | - | $a - $b | 12 |
| Multiplication | * | $a * $b | 85 |
| Division | / | $a / $b | 3.4 |
| Modulus (remainder) | % | $a % $b | 2 |
| Exponentiation | ** | $a ** 2 | 289 |
| Negation | - | -$a | -17 |
<?php $a = 17; $b = 5; echo "a + b = " . ($a + $b) . "<br>"; echo "a - b = " . ($a - $b) . "<br>"; echo "a * b = " . ($a * $b) . "<br>"; echo "a / b = " . ($a / $b) . "<br>"; echo "a % b = " . ($a % $b) . "<br>"; echo "a ** 2 = " . ($a ** 2) . "<br>"; echo "intdiv(a, b) = " . intdiv($a, $b); ?>
a + b = 22 a - b = 12 a * b = 85 a / b = 3.4 a % b = 2 a ** 2 = 289 intdiv(a, b) = 3
Comparison Operators
A comparison returns a boolean – true or false.
| Operator | Symbol | True when … |
|---|---|---|
| Equal | == | values are equal after type juggling |
| Identical | === | values are equal and of the same data type |
| Not equal | != or <> | values are not equal |
| Not identical | !== | values differ or the types differ |
| Less than | < | left is smaller |
| Greater than | > | left is bigger |
| Less than or equal to | <= | left is smaller or equal |
| Greater than or equal to | >= | left is bigger or equal |
| Spaceship | <=> | returns -1, 0 or 1 (less, equal, greater) |
<?php $x = 5; // integer $y = "5"; // string echo "<pre>"; echo '$x == $y : '; var_dump($x == $y); echo '$x === $y : '; var_dump($x === $y); echo '$x != 8 : '; var_dump($x != 8); echo '$x !== $y : '; var_dump($x !== $y); echo '$x >= 5 : '; var_dump($x >= 5); echo '3 <=> 7 : '; var_dump(3 <=> 7); echo '7 <=> 7 : '; var_dump(7 <=> 7); echo "</pre>"; ?>
$x == $y : bool(true) $x === $y : bool(false) $x != 8 : bool(true) $x !== $y : bool(true) $x >= 5 : bool(true) 3 <=> 7 : int(-1) 7 <=> 7 : int(0)
Prefer === and !== when you compare values that may be of different types, such as the result of strpos() (which can return 0 or false). PHP 8 also made 0 == "abc" false (in PHP 7 it was true), which removed a classic source of bugs.
Logical Operators
| Operator | Symbol | Result |
|---|---|---|
| And | && or and | true if both operands are true |
| Or | || or or | true if at least one operand is true |
| Xor | xor | true if only one of the two is true |
| Not | ! | true if the operand is false |
<?php $age = 20; $hasId = true; echo "<pre>"; echo "age >= 18 && hasId : "; var_dump($age >= 18 && $hasId); echo "age < 18 || hasId : "; var_dump($age < 18 || $hasId); echo "true xor true : "; var_dump(true xor true); echo "!hasId : "; var_dump(!$hasId); echo "</pre>"; ?>
age >= 18 && hasId : bool(true) age < 18 || hasId : bool(true) true xor true : bool(false) !hasId : bool(false)
Increment and Decrement Operators
| Operator | Example | Meaning |
|---|---|---|
| Pre-increment | ++$v | add 1, then return the new value |
| Post-increment | $v++ | return the current value, then add 1 |
| Pre-decrement | --$v | subtract 1, then return the new value |
| Post-decrement | $v-- | return the current value, then subtract 1 |
<?php $v = 5; echo "v++ gives " . $v++ . ", now v = $v<br>"; echo "++v gives " . ++$v . ", now v = $v<br>"; echo "v-- gives " . $v-- . ", now v = $v<br>"; echo "--v gives " . --$v . ", now v = $v"; ?>
v++ gives 5, now v = 6 ++v gives 7, now v = 7 v-- gives 7, now v = 6 --v gives 5, now v = 5
The Concatenation Operator
The concatenation "operator" is a period (full stop). It simply says "join this to this":
<?php $parta = "This is part one"; $partb = " of a sentence!"; print $parta . $partb; echo "<br>"; $msg = "PHP"; $msg .= " and MySQLi"; // .= appends to the variable echo $msg; ?>
This is part one of a sentence! PHP and MySQLi
Combined (Assignment) Operators
= is the assignment operator: $a = 5 assigns the value 5 to $a. It can be combined with other operators. If $a is 5, then after $a += 5 it is 10 – exactly as if you had written $a = $a + 5. Some programmers like combined operators because they reduce typing; use whichever form you find clearer.
| Operator | Example | Same as |
|---|---|---|
| += | $d1 += 3 | $d1 = $d1 + 3 |
| -= | $d1 -= 3 | $d1 = $d1 - 3 |
| *= | $d1 *= 3 | $d1 = $d1 * 3 |
| /= | $d1 /= 3 | $d1 = $d1 / 3 |
| %= | $d1 %= 3 | $d1 = $d1 % 3 |
| .= | $s .= "x" | $s = $s . "x" |
| ??= | $n ??= 1 | $n = $n ?? 1 |
<?php $d1 = 12; $d1 += 3; echo "After += 3 : $d1<br>"; $d1 -= 5; echo "After -= 5 : $d1<br>"; $d1 *= 2; echo "After *= 2 : $d1<br>"; $d1 /= 4; echo "After /= 4 : $d1<br>"; $d1 %= 3; echo "After %= 3 : $d1"; ?>
After += 3 : 15 After -= 5 : 10 After *= 2 : 20 After /= 4 : 5 After %= 3 : 2
Other Useful Operators
- Ternary
?:–$result = (condition) ? value_if_true : value_if_false; - Null coalescing
??(PHP 7) –$name = $_GET['name'] ?? 'Guest';gives the left value if it exists and is notnull, otherwise the right value. Very handy for reading form fields. - Error control
@– suppresses error messages of an expression (use rarely).
<?php $marks = 72; echo "Result: " . ($marks >= 40 ? "Pass" : "Fail") . "<br>"; $name = $_GET['name'] ?? 'Guest'; $city = $_GET['city'] ?? 'Unknown'; echo "Name: $name, City: $city"; ?>
Result: Pass Name: Ravi, City: Unknown
Precedence and Associativity
Think about this operation: $a = 7 - 4 + 1. If the minus happens before the plus, the result is 4; if the plus happens first, the result is 2. Since predictability is essential, an order of precedence was established, together with associativity.
- Precedence gives each operator a rank: operators with higher rank are evaluated first.
- When several operators have the same rank, associativity decides: left-associative operators are processed from left to right, right-associative operators from right to left. Some operators, such as the comparison operators, are non-associative.
The order of precedence of the operators in this chapter, from highest to lowest (operators on one line have equal precedence):
| Rank | Operators |
|---|---|
| 1 | ** |
| 2 | ++ -- (int) (float) (string) (bool) @ |
| 3 | ! |
| 4 | * / % |
| 5 | + - |
| 6 | . (concatenation – lower than + and - since PHP 8) |
| 7 | < <= > >= |
| 8 | == != === !== <> <=> |
| 9 | && |
| 10 | || |
| 11 | ?? |
| 12 | ? : (ternary) |
| 13 | = += -= *= /= .= %= ??= |
| 14 | and |
| 15 | xor |
| 16 | or |
You can override precedence with parentheses – the innermost parentheses are processed first:
<?php echo "7 - 4 + 1 = " . (7 - 4 + 1) . "<br>"; echo "(7 - 4) + 1 = " . ((7 - 4) + 1) . "<br>"; echo "7 - (4 + 1) = " . (7 - (4 + 1)) . "<br>"; echo "2 + 3 * 3 = " . (2 + 3 * 3) . "<br>"; echo "2 + (3 * 3) = " . (2 + (3 * 3)) . "<br>"; echo "(2 + 3) * 3 = " . ((2 + 3) * 3) . "<br>"; echo "1 + 3 + 3 * 2 = " . (1 + 3 + 3 * 2) . "<br>"; echo "1 + ((3 + 3) * 2) = " . (1 + ((3 + 3) * 2)) . "<br>"; echo "(1 + (3 + 3)) * 2 = " . ((1 + (3 + 3)) * 2); ?>
7 - 4 + 1 = 4 (7 - 4) + 1 = 4 7 - (4 + 1) = 2 2 + 3 * 3 = 11 2 + (3 * 3) = 11 (2 + 3) * 3 = 15 1 + 3 + 3 * 2 = 10 1 + ((3 + 3) * 2) = 13 (1 + (3 + 3)) * 2 = 14
Use parentheses whenever you write a complex expression. It makes the code easier to read when you come back to it months or years later – and it never changes a correct result.
Key Takeaways
- Arithmetic:
+ - * / % **; comparison:== === != !== < > <= >= <=>; logical:&& || xor !. ==compares values after conversion;===also compares the data type.$v++returns the old value,++$vthe new value.- The dot
.joins strings;.=appends. - Combined operators such as
+=are shorthand for$a = $a + …. ??supplies a default for missing values;?:chooses between two values.- Precedence and associativity decide evaluation order; parentheses override them.
Program File
Extract the ZIP into C:\xampp\htdocs. It creates the folder phpbook/ch05 used in the file labels above; open the programs at http://localhost/phpbook/… with Apache (and MySQL, where needed) started in the XAMPP Control Panel.
Question / Answer (15 questions)
MCQ Test : Check Your Understanding (5 questions)
Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.
Bibliography/References
The notes on this page are the author’s own compilation from the e-book PHP: Basics to Advance. Every program was run on Apache with PHP 8 and MariaDB, and the output shown is the real result of that run. The works listed below were consulted and are cited for attribution and further reading. Product names and trademarks belong to their respective owners.
- The PHP Group. (n.d.). PHP Manual – Operators. https://www.php.net/manual/en/language.operators.php
- The PHP Group. (n.d.). PHP Manual – Operator Precedence. https://www.php.net/manual/en/language.operators.precedence.php
- The PHP Group. (n.d.). PHP Manual – Comparison Operators. https://www.php.net/manual/en/language.operators.comparison.php
- The PHP Group. (n.d.). PHP Manual – Backward incompatible changes (PHP 8.0). https://www.php.net/manual/en/migration80.incompatible.php