Home Quizzes Leaderboard Competitions Learn Hire Us
About Contact
Log In Sign Up
Learn PHP Operators & Math

Operators & Math

⏱ 12 min read read
Arithmetic Operators:

+ (addition) - (subtraction) * (multiplication)

/ (division) % (modulus) ** (exponent, PHP 5.6+)

intdiv(a, b) --- integer division (no floor division operator)

PHP DIFFERENCE: PHP uses / for division and it returns int if both

operands are int and the result is whole, otherwise float.

10 / 2 = 5 (int) 10 / 3 = 3.333... (float)

Use intdiv(10, 3) for integer division (= 3). No // operator like
Python.

PHP HAS ++ and -- operators (unlike Python)!

Assignment Operators:

$x += 5; // $x = $x + 5

$x -= 3; // $x = $x - 3

$x *= 2; // $x = $x * 2

$x /= 4; // $x = $x / 4

$x **= 2; // $x = $x ** 2

$x++; // increment (PHP has this, Python does not!)

$x--; // decrement

$s .= " world"; // string concatenation assignment

Comparison Operators:

== (equal, loose) === (identical, strict) != or <> (not equal)

!== (not identical) < > <= >=

<=> (spaceship operator, PHP 7+): returns -1, 0, or 1

Logical Operators:

&& or and --- both conditions must be true

|| or or --- at least one must be true

! or not --- flips true/false

Math Functions:

abs(-42) // 42

sqrt(144) // 12

pow(2, 10) // 1024

ceil(3.2) // 4

floor(3.9) // 3

round(3.567, 2) // 3.57

max(1, 5, 3) // 5

min(1, 5, 3) // 1

M_PI // 3.14159...

rand(1, 6) // random int 1--6 (like dice roll)
Code Example
<?php

$a = 10;

$b = 3;

echo $a + $b . "\n"; // 13

echo $a - $b . "\n"; // 7

echo $a * $b . "\n"; // 30

echo $a / $b . "\n"; // 3.3333...

echo intdiv($a, $b) . "\n"; // 3 (integer division)

echo $a % $b . "\n"; // 1 (remainder)

echo $a ** $b . "\n"; // 1000 (exponent)

// Shorthand (PHP HAS ++ and --!)

$x = 10;

$x += 5;

$x--;

$x *= 2;

echo $x . "\n"; // 28

// Comparison --- ALWAYS use ===

var_dump($a == "10"); // bool(true) --- LOOSE, dangerous

var_dump($a === "10"); // bool(false) --- STRICT, safe

// Spaceship operator

echo (5 <=> 10) . "\n"; // -1

echo (10 <=> 10) . "\n"; // 0

echo (15 <=> 10) . "\n"; // 1

// Logical

$isAdult = true;

$hasTicket = false;

var_dump($isAdult && $hasTicket); // bool(false)

var_dump($isAdult || $hasTicket); // bool(true)

var_dump(!$isAdult); // bool(false)

// Math functions

echo sqrt(144) . "\n"; // 12

echo pow(2, 10) . "\n"; // 1024

echo round(3.567, 2) . "\n"; // 3.57

echo abs(-42) . "\n"; // 42

// Dice roll

$dice = rand(1, 6);

echo "Dice: $dice\n";

?>
← Variables & Data Types If Statements & Conditionals →

Log in to track your progress and earn badges as you complete lessons.

Log In to Track Progress