PHP ยท Chapter 12 of 44

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.

Syntax
$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.

Example 1 (php)
<?php
  var_dump(0 == "a");
  var_dump(0 === "a");
?>
Output
bool(false)
bool(false)

In modern PHP, comparing 0 to a non-numeric string is false with both == and ===.

Example 2 (php)
<?php
  $age = 20;
  if ($age > 18 && $age < 65) {
    echo "Working age";
  }
?>
Output
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.
๐Ÿ’ก Note: Prefer === over == in most cases to avoid unexpected type-conversion surprises.

๐Ÿ“ Quick Quiz

1. What does === check that == does not?

2. Which operator means logical AND?

3. What does the % operator do?