PHP Operators
Operators are the symbols PHP uses to combine, compare, and transform values so your scripts can calculate results and make decisions.
What operators do
An operator is a symbol that tells PHP to perform an action on one or more values. The values an operator works on are called operands. Most operators sit between two operands, such as the plus sign in $a + $b, while a few work on a single value or on three parts. PHP groups its operators into families based on the job they do: arithmetic for math, assignment for storing results, comparison for testing values, logical for combining conditions, and a handful of specialised operators for strings and null handling.
Arithmetic operators
Arithmetic operators perform ordinary mathematics on numbers. Alongside the four you already know from school, PHP adds the modulus operator for remainders and the exponentiation operator for powers.
Arithmetic in action
<?php
$price = 250;
$quantity = 4;
$subtotal = $price * $quantity; // 1000
$tax = $subtotal * 0.18; // 180
$total = $subtotal + $tax; // 1180
echo "Total: " . $total . PHP_EOL;
echo "Is quantity even? remainder = " . ($quantity % 2); // 0
?>Assignment operators
The basic assignment operator = stores the value on its right into the variable on its left. Combined assignment operators let you update a variable in place, so $total += 50 is a shorter way of writing $total = $total + 50. The same shorthand exists for every arithmetic operator and for string concatenation.
Compound assignment
<?php
$score = 100;
$score += 20; // 120
$score -= 5; // 115
$score *= 2; // 230
$score /= 10; // 23
$greeting = "Hello";
$greeting .= ", world"; // "Hello, world"
echo $score . PHP_EOL;
echo $greeting;
?>Comparison operators
Comparison operators test a relationship between two values and always return a boolean, either true or false. The distinction between loose and strict comparison matters a lot in PHP: == checks only that the values are equal after PHP converts them to a common type, while === also requires that the types match exactly. Preferring the strict versions avoids surprises where a string and a number are treated as equal.
Logical and other operators
- Logical AND (&&) is true only when both sides are true.
- Logical OR (||) is true when at least one side is true.
- Logical NOT (!) flips a boolean, turning true into false and back.
- The concatenation operator (.) joins two strings into one.
- The null coalescing operator (??) returns its left side unless it is null or undefined, in which case it returns the right side.
Logical and null coalescing
<?php
$age = 22;
$hasTicket = true;
if ($age >= 18 && $hasTicket) {
echo "Entry allowed" . PHP_EOL;
}
// Fall back to a default when a value is missing
$username = $_GET["user"] ?? "guest";
echo "Welcome, " . $username;
?>Exercise: PHP Operators
What is the key difference between == and === in PHP?