Operators
Do maths and comparisons — the building blocks of logic.
What you will learn
- Use arithmetic operators
- Compare values
- Combine conditions
Arithmetic & assignment
Operators are the symbols that do work on values — adding, subtracting, comparing. The arithmetic ones (+ - * /) do everyday maths. The example below also shows % (remainder) and the += shortcut.
<?php
$a = 10;
$b = 3;
echo $a + $b; // 13
echo $a % $b; // 1 (remainder)
$a += 5; // $a is now 15
?>Walking through it: $a + $b adds 10 and 3 to give 13. $a % $b is the modulo operator — it gives the remainder after dividing (10 ÷ 3 is 3 with 1 left over, so the answer is 1). The last line, $a += 5, is shorthand for $a = $a + 5, so $a grows from 10 to 15.
Note: Output (in the browser):
131
The two echo values print next to each other with nothing between them: 13 then 1. The $a += 5 line only changes the variable; it does not print anything by itself.
Tip: The % (remainder) operator is the classic way to test even/odd: if $n % 2 is 0 the number is even, otherwise it is odd.
Comparison & logical
Comparison operators ask a yes/no question about two values and answer with true or false. Logical operators (&&, ||) join several yes/no answers together. These are what every if statement relies on.
| Operator | Means |
|---|---|
== | Equal in value |
=== | Equal in value AND type (preferred) |
!= | Not equal |
> < >= <= | Comparisons |
&& / and | AND |
|| / or | OR |
Here they are in action. A comparison gives back true or false; true prints as 1 and false prints as nothing, so we wrap them in words to make the result clear:
<?php
$age = 20;
var_dump($age > 18); // bool(true) — 20 is greater than 18
var_dump($age === 20); // bool(true) — same value and type
var_dump($age === "20"); // bool(false) — value matches but type does not
var_dump($age > 18 && $age < 30); // bool(true) — both sides are true
?>Note: Output (in the browser):
bool(true)
bool(true)
bool(false)
bool(true)
var_dump() is a handy tool that prints a value *with its type* so you can see exactly what came back. Notice line 3: 20 (a number) is not strictly equal to "20" (text), so === gives false. The last line is true only because both $age > 18 AND $age < 30 are true.
Tip: Prefer === over == — it also checks the type, avoiding surprises (e.g. 0 == "abc" behaves oddly in PHP, but === is strict and safe).
Q. Which operator checks both value AND type?
✍️ Practice
- Calculate the total price of items and print it.
- Compare two numbers with
===and print whether they are equal.
🏠 Homework
- Write a script that checks if a number is even using
%.