Skip to content

PHP Operators — Complete Guide to Arithmetic, Comparison, and Logical Operators

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about PHP Operators. We cover key concepts, practical examples, and best practices to help you master this topic.

PHP operators perform operations on values and variables, supporting arithmetic calculations, comparison checks, logical combinations, and specialized operators for common tasks.

What You'll Learn

By the end of this tutorial, you'll use all PHP operator types: arithmetic, comparison, logical, assignment, string, array, ternary, null coalescing, and spaceship operators.

Why PHP Operators Matter

Operators are the building blocks of expressions. Every PHP script uses them for calculations, condition checks, and data manipulation. Knowing operator precedence prevents logic bugs.

Real-World Use

A shopping cart uses arithmetic operators for totals, comparison operators for stock checks, logical operators for discount eligibility, and null coalescing for default values.

PHP Operators Learning Path

flowchart LR
  A[Numbers] --> B[Operators]
  B --> C[Boolean Logic]
  C --> D[Control Flow]
  D --> E[Loops]
  A --> F{You Are Here}
  style F fill:#f90,color:#fff

Arithmetic Operators

<?php
echo 10 + 3;   // 13 (addition)
echo 10 - 3;   // 7 (subtraction)
echo 10 * 3;   // 30 (multiplication)
echo 10 / 3;   // 3.333... (division)
echo 10 % 3;   // 1 (modulus)
echo 10 ** 3;  // 1000 (exponentiation)

Comparison Operators

<?php
var_dump(5 == "5");   // true (loose equality)
var_dump(5 === "5");  // false (strict equality)
var_dump(5 != "5");   // false (loose inequality)
var_dump(5 !== "5");  // true (strict inequality)
var_dump(5 > 3);      // true
var_dump(5 <=> 3);    // 1 (spaceship: returns -1, 0, or 1)
var_dump(3 <=> 5);    // -1
var_dump(5 <=> 5);    // 0

Logical Operators

<?php
$a = true;
$b = false;
var_dump($a && $b);  // false (AND)
var_dump($a || $b);  // true (OR)
var_dump(!$a);       // false (NOT)
var_dump($a and $b); // false (low precedence AND)
var_dump($a xor $b); // true (XOR)

Null Coalescing Operator

<?php
$username = $_GET["user"] ?? "guest";  // Use "guest" if not set
$name = $firstName ?? $lastName ?? "Anonymous";  // Chain defaults
$value = $data["key"] ?? fallback();

Ternary Operator

<?php
$age = 20;
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status;  // Adult

// Short ternary (PHP 7+)
$name = $input ?: "Anonymous";  // Same as $input ? $input : "Anonymous"

String and Array Operators

<?php
// String
echo "Hello " . "World";  // Hello World (concatenation)
$text = "Hello ";
$text .= "World";          // Hello World (append)

// Array
$a = ["a" => 1, "b" => 2];
$b = ["c" => 3];
print_r($a + $b);  // Union: ["a"=>1, "b"=>2, "c"=>3]
var_dump($a == $b);  // false (same key/value pairs)

Common Mistakes

1. Using = Instead of == in Conditions

if ($x = 5) assigns 5 to $x and is always truthy. Always use == or === for comparison.

2. Operator Precedence Confusion

<?php
$result = true || false && false;
// && has higher precedence than ||, so: true || (false && false) = true
var_dump($result);  // true

3. Forgetting the Null Coalescing Chain

Use ?? for safe default chaining instead of nested ternary which is hard to read.

4. Using AND/OR Instead of &&/|| in Expressions

<?php
$x = true and false;  // $x = true, because = has higher precedence than and
$y = true && false;    // $y = false

5. Modulus with Negative Numbers

-5 % 3 = -2 in PHP. For positive remainder, use abs() or adjust.

Practice Questions

1. What is the difference between == and ===?

== checks value equality with type conversion. === checks value and type identity without conversion.

2. What does the spaceship operator <=> do?

It returns -1 if left < right, 0 if equal, 1 if left > right. Used for sorting comparisons.

3. What is the null coalescing operator ?? used for?

It returns the left operand if it exists and is not null, otherwise the right operand. Useful for defaults.

4. What is operator precedence?

The order in which operators are evaluated. Multiplication has higher precedence than addition: 2 + 3 * 4 = 14.

5. Challenge: Write an expression that checks if a year is a leap year using logical operators.

<?php
function isLeapYear(int $year): bool {
    return ($year % 4 === 0 && $year % 100 !== 0) || $year % 400 === 0;
}
var_dump(isLeapYear(2024));  // true
var_dump(isLeapYear(2025));  // false

FAQ

What is the difference between AND and &&?

Both are logical AND. && has higher precedence. AND is useful for readability in certain contexts.

What does the @ operator do?

The error control operator @ suppresses error messages for the expression it precedes. Use it sparingly.

What is instance of operator?

instanceof checks if a variable is an instance of a specific class: $obj instanceof User.

Can I overload operators in PHP?

PHP doesn't support operator overloading for user-defined classes (unlike C++).

What is the execution operator ``?

Backticks execute shell commands: $output = ls -la; Same as shell_exec().

Mini Project: Discount Calculator

Build a discount calculator using various operators.

<?php
function calculateDiscount(float $price, string $customerType, int $itemsCount): float {
    $discount = 0.0;
    if ($customerType === "vip") $discount += 0.1;
    if ($itemsCount >= 5) $discount += 0.05;
    $discount = min($discount, 0.3);  // Max 30% off
    return round($price * (1 - $discount), 2);
}
echo calculateDiscount(100, "regular", 3);   // 100.0
echo calculateDiscount(100, "vip", 5);       // 85.0
echo calculateDiscount(100, "vip", 20);      // 85.0 (capped)

What's Next

PHP Boolean Logic PHP Control Flow PHP Arrays

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro