PHP Operators
Operators are symbols used to perform operations on variables and values. PHP supports arithmetic operators (+, -, *, /, %), assignment operators (=, +=, -=), comparison operators (==, ===, !=, <, >), and logical operators (&&, ||, !).
Understanding the difference between == (loose comparison) and === (strict comparison, which also checks type) is especially important in PHP because of its loosely typed nature.
$a == $b;
$a === $b;
$a && $b;Comparison operators
== checks if values are equal after type conversion, while === checks both value and type. Similarly, != and !== check for inequality with and without type checking.
Logical operators
&& (and) requires both conditions to be true, || (or) requires at least one to be true, and ! negates a boolean value.
<?php
var_dump(0 == "a");
var_dump(0 === "a");
?>bool(false)
bool(false)In modern PHP, comparing 0 to a non-numeric string is false with both == and ===.
<?php
$age = 20;
if ($age > 18 && $age < 65) {
echo "Working age";
}
?>Working age&& requires both comparisons to be true for the if block to run.
Key points
- Arithmetic operators include +, -, *, /, and % (modulus).
- == compares value only; === compares value and type.
- &&, || and ! are the main logical operators.
- Assignment operators like += update a variable based on its current value.
