PHP Operators
Operators are symbols that do something with values, like adding two numbers or comparing them. In $a + $b, the plus sign is the operator, and $a and $b are the operands.
Arithmetic operators
| Operator | Name | Example |
|---|---|---|
| + | Addition | $a + $b |
| – | Subtraction | $a – $b |
| * | Multiplication | $a * $b |
| / | Division | $a / $b |
| % | Modulus (remainder) | $a % $b |
| ** | Exponentiation (power) | $a ** $b |
Details with output are in arithmetic operators and division vs modulus.
Assignment operators
| Operator | Same as |
|---|---|
| $a = 5 | Assign 5 to $a |
| $a += 3 | $a = $a + 3 |
| $a -= 3 | $a = $a – 3 |
| $a *= 3 | $a = $a * 3 |
| $a .= “x” | $a = $a . “x” (join text) |
| $a ??= 1 | Set $a only if it is not set or null |
Comparison operators
| Operator | Name | True when |
|---|---|---|
| == | Equal | Values are same |
| === | Identical | Values and data types are same |
| != or <> | Not equal | Values are different |
| !== | Not identical | Values or data types are different |
| < , > , <= , >= | Less, greater… | The usual comparison |
| <=> | Spaceship | Returns -1, 0 or 1 |
Learn the strict ones in == vs === and != vs !==.
Increment and decrement
++$a and $a++ add 1, --$a and $a-- subtract 1. The difference is explained in $var++ vs $var + 1.
Logical operators
| Operator | Name | True when |
|---|---|---|
| && (and) | And | Both sides are true |
| || (or) | Or | At least one side is true |
| ! | Not | The value is false |
| xor | Xor | Only one side is true |
Other useful operators
- String join: the dot (
.) joins two strings. - Array union:
$a + $bjoins two arrays. - Ternary:
condition ? a : b. See PHP Ternary Operator. - Null coalescing:
$a ?? "default". See the ?? operator.
Example
<?php
$a = 10;
$b = 3;
echo ($a + $b) . "<br>";
echo ($a % $b) . "<br>";
var_dump("5" == 5);
var_dump("5" === 5);
var_dump($a <=> $b);
$text = "Hello";
$text .= " PHP";
echo $text . "<br>";
$user = null;
echo $user ?? "Guest";
?>
Output:
Tutorials Class - Output Window
13
1
bool(true)
bool(false)
int(1)
Hello PHP
Guest
Note:
When many operators are in one line, PHP follows an order (precedence), for example multiplication goes before addition. Use brackets to make it clear.
Next chapter: PHP Decision Making.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| Write a PHP program to add two numbers |
| Write a PHP program to check whether a number is positive, negative or zero |