Lessons → PHP Basics → Lesson 3

Operators

PHP
⏱ 10 min read📖 BeginnerNot completed

Operators are symbols that perform operations on variables and values. PHP has several types of operators — let's cover them all.

Arithmetic Operators

PHP
<?php
$a = 10;
$b = 3;

echo $a + $b;   // 13  — Addition
echo $a - $b;   // 7   — Subtraction
echo $a * $b;   // 30  — Multiplication
echo $a / $b;   // 3.33 — Division
echo $a % $b;   // 1   — Modulus (remainder)
echo $a ** $b;  // 1000 — Exponentiation (10^3)
?>

Assignment Operators

PHP
<?php
$x = 10;     // Assign
$x += 5;     // $x = $x + 5  → 15
$x -= 3;     // $x = $x - 3  → 12
$x *= 2;     // $x = $x * 2  → 24
$x /= 4;     // $x = $x / 4  → 6
$x %= 4;     // $x = $x % 4  → 2
$x **= 3;    // $x = $x ** 3 → 8

$str = "Hello";
$str .= " World";  // $str = $str . " World" → "Hello World"
?>

Comparison Operators

OperatorNameExampleResult
==Equal5 == "5"true
===Identical5 === "5"false
!=Not equal5 != 3true
!==Not identical5 !== "5"true
>Greater than5 > 3true
<Less than5 < 3false
>=Greater or equal5 >= 5true
<=Less or equal3 <= 5true
<=>Spaceship5 <=> 31

Logical Operators

PHP
<?php
$a = true;
$b = false;

var_dump($a && $b);   // false — AND (both must be true)
var_dump($a || $b);   // true  — OR (at least one true)
var_dump(!$a);        // false — NOT (opposite)
var_dump($a and $b);  // false — AND (same as &&)
var_dump($a or $b);   // true  — OR (same as ||)
var_dump($a xor $b);  // true  — XOR (one true, not both)
?>

Increment / Decrement

PHP
<?php
$x = 5;

echo $x++;  // 5 — returns then increments
echo $x;    // 6

echo ++$x;  // 7 — increments then returns
echo $x;    // 7

echo $x--;  // 7 — returns then decrements
echo --$x;  // 5 — decrements then returns
?>

String Operator

PHP
<?php
$first = "Hello";
$last = "World";

// Concatenation
echo $first . " " . $last;  // Hello World

// Concatenation assignment
$first .= " World";
echo $first;  // Hello World
?>
💡
Spaceship operator <=>: Returns -1 if left is less, 0 if equal, 1 if greater. Very useful for sorting: usort($arr, fn($a, $b) => $a <=> $b)
← Previous Lesson Next Lesson →
🧠

Test your knowledge!

Take the PHP Basics quiz.

Take Quiz →