AnyCompiler

Numbers and Operators

PHP's arithmetic operators are the usual +, -, *, /, and % for remainder, plus intdiv() for integer (floor) division when you specifically don't want a float back. All of that is unsurprising. What is genuinely distinctive — and has a well-earned reputation as PHP's signature gotcha — is the difference between == and ===.

== ("loose equality") converts its two operands toward a common type before comparing them — this is called type juggling. === ("strict equality") never converts anything: it only returns true when both the value and the type already match. The two operators can disagree on the exact same pair of values, and this course would rather show you a real, actually-executed example of that than describe it in the abstract.

<?php
$a = 17;
$b = 5;
echo "Sum: " . ($a + $b) . "\n";
echo "Mod: " . ($a % $b) . "\n";
echo "Div: " . ($a / $b) . "\n";
echo "IntDiv: " . intdiv($a, $b) . "\n";

var_dump(1 == "1");
var_dump(1 === "1");
var_dump(0 == "abc");
var_dump(0 === "abc");
Output
Sum: 22
Mod: 2
Div: 3.4
IntDiv: 3
bool(true)
bool(false)
bool(true)
bool(false)

1 == "1" is true — unsurprising, since the string "1" juggles cleanly into the integer 1 — but 1 === "1" is false, because an int and a string are never the same type no matter what they look like. The genuinely surprising line is 0 == "abc": on this site's confirmed runtime, PHP 7.4.1, that's true. "abc" isn't a numeric string at all, but PHP 7.4's type-juggling rules still convert it to 0 for the comparison — meaning a non-numeric string loosely equals the number zero. (PHP 8.0 changed exactly this rule — the same comparison evaluates to false there — but this course runs on 7.4.1, and this result is what that runtime actually, verifiably does, not what a newer version would do.) 0 === "abc" is false either way, because strict equality never juggles types to begin with. The practical takeaway nearly every PHP style guide repeats: default to === unless you have a specific reason to want type juggling. Next: arrays — PHP's indexed arrays and the array functions built around them.

Practice exercise

Given $a = 9 and $b = 2, echo $a % $b on its own line, then var_dump($a === 9).