Basics Lesson 6 of 17
PHP Operators and Math Functions
Arithmetic, assignment, comparison (== vs ===), logical, string and null-coalescing operators in PHP, plus round, floor, ceil, max, min, rand and intdiv.
PHP's operators look like those in C and JavaScript, with two PHP-specific ones you'll use all the time: . for joining strings and ?? for default values.
Arithmetic
<?php
$minutes = 135;
echo intdiv($minutes, 60), " hr ", $minutes % 60, " min\n";
echo 2 ** 10, "\n";
echo 7 / 2, "\n";
echo (88 + 91 + 85) / 3, "\n";
Output
2 hr 15 min 1024 3.5 88
/ gives a decimal when needed; intdiv() gives a whole-number result. ** is the power operator.
Assignment
<?php
$score = 10;
$score += 5;
$score *= 2;
$score--;
$msg = "Score";
$msg .= ": $score";
echo $msg;
Output
Score: 29
Comparison: == vs ===
<?php
var_dump(5 == "5");
var_dump(5 === "5");
var_dump(0 == "");
var_dump(null == false);
var_dump(5 != 3, 5 !== "5");
var_dump(3 <=> 5);
Output
bool(true) bool(false) bool(false) bool(true) bool(true) bool(true) int(-1)
==compares values after converting types ("loose").===also requires the same type ("strict").<=>(spaceship) returns -1, 0 or 1; it's useful for sorting.
Logical operators
<?php
$average = 92;
$lowest = 86;
$age = 17;
var_dump($average >= 90 && $lowest >= 85);
var_dump($age < 18 || $age >= 60);
var_dump(!($age >= 18));
Output
bool(true) bool(true) bool(true)
PHP also has and and or, but they have lower priority than =, which causes subtle bugs. Stick with && and ||.
Null coalescing
<?php
$settings = ["theme" => "dark"];
echo $settings["theme"] ?? "light", "\n";
echo $settings["fontSize"] ?? 16, "\n";
echo $_GET["page"] ?? "home";
Output
dark 16 home
?? returns the left value if it exists and isn't null, otherwise the right. It's perfect for reading form values that may be missing.
Math functions
<?php
echo round(88.456, 2), "\n";
echo round(89.5), "\n";
echo floor(9.99), " ", ceil(41 / 5), "\n";
echo max(88, 95, 79), " ", min([88, 95, 79]), "\n";
echo abs(-15), " ", sqrt(144), "\n";
echo number_format(pi(), 4), "\n";
echo random_int(1, 6), "\n";
Output
88.46 90 9 9 95 79 15 12 3.1416 4
random_int(1, 6) gives a secure random number including both ends; your result will differ. rand() and mt_rand() also exist.
The ternary operator
<?php
$grade = 79;
echo $grade >= 75 ? "PASSED" : "FAILED";
Output
PASSED
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04