The Analogy: The Weighbridge At The Scrapyard
A scrapyard buys metal by weight. A lorry drives onto the weighbridge, the plate under the wheels settles, and the machine prints a docket: a number, and nothing else. Beside the bridge the yard hand chalks a word on the side of each skip -- COPPER, CARDBOARD, MIXED -- so the clerk in the hut knows what the number refers to. The chalk is not enforced by anything. It is a label written on the outside of a container, and if somebody wipes it off and writes a different word, the skip does not object. The clerk works from the docket and the chalk, and the yard runs perfectly well on that arrangement for decades.
PHP works this way, and the arrangement has a name: dynamic typing. The variable is the chalk mark, not the container. Writing $load = "12500" does not make $load a string variable; it puts a value that happens to be a string into a peg called $load, and the value is what carries the type tag. The next line may put an integer in the same peg, then an array, then null, and none of it is an error. Two functions read the tag rather than guessing: gettype() returns the historical name, so a float reports as double, and get_debug_type() returns the modern name you would write in code, which is float. When you hear that PHP is untyped, this is what is actually meant -- the variables are untyped, while every value knows exactly what it is.
The interesting machinery is what happens when two loads have to be combined, because that is decided by the operation and not by the loads. Ask for a weight and the yard uses the weighbridge; ask for a description and it uses the label board; ask the gateman a yes-or-no question and he glances at the skip and decides. PHP has the same three benches, called contexts. + puts both operands in numeric context, so "10" + 5 is 15. . puts them in string context, so "10" . 5 is "105". An if puts a single value in boolean context, so "", "0", 0, [], and null are all treated as no. The conversions are performed automatically and this is what the language calls type juggling. It is convenient exactly as often as it is dangerous, because nothing in the code says which bench a value was carried to.
The failure mode is the clerk who squints at a bad docket. Somebody writes "twelve tonnes" on the weight line, and rather than refusing it the old clerk reads a 12 and files it, or reads a zero and files that. PHP behaved this way for twenty years: before version 8, 0 == "twelve tonnes" was true, because the string was converted to a number and a word converted to zero. Any check that compared a numeric identifier against a submitted string could therefore pass by accident, which is precisely how a series of real authentication bypasses worked. PHP 8 changed the rule so that comparing a number against a non-numeric string compares them as strings instead, and 0 == "twelve tonnes" is now false. That helps, and it does not remove the underlying hazard, because the conversion is still silent everywhere else. The discipline that does remove it is boring and effective: validate once at the boundary where data arrives, convert deliberately, and keep the types honest from then on, with declare(strict_types=1) making the compiler refuse to squint on your behalf.
Syntax or Core Structure
A variable is a dollar sign followed by a name, with no declaration and no type keyword. Names are case-sensitive, may hold anything, and spring into existence on first assignment.
<?php
declare(strict_types=1);
$name = "Ada";
$count = 42;
$rate = 0.5;
$active = true;
$tags = ["a", "b"];
$nothing = null;
var_dump($name, $count, $rate, $active, $tags, $nothing);
echo gettype($rate), " ", get_debug_type($rate), PHP_EOL;
Output:
string(3) "Ada"
int(42)
float(0.5)
bool(true)
array(2) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
}
NULL
double float
var_dump is the tool to reach for while learning, because it prints the type and, for strings, the byte length: string(3) "Ada" tells you far more than echo would. Note the last line, which is a small piece of PHP history you will trip over. gettype() was written when floats were called doubles and it still says double; get_debug_type() arrived in PHP 8 and says float, matching what you type in a type declaration. Prefer get_debug_type() in new code, especially in error messages, because it also reports class names rather than the useless word object.
Juggling is easiest to understand by watching it happen. Every line below is legal PHP, and the interesting part is which bench each value was carried to.
<?php
declare(strict_types=1);
var_dump("10" + 5);
var_dump("10" . 5);
var_dump(1 + 1.0);
var_dump("3" == 3);
var_dump("3" === 3);
var_dump("abc" == 0);
var_dump(0 == "");
var_dump("1e3" == "1000");
var_dump(null == false);
var_dump("0" ? "yes" : "no");
var_dump("0.0" ? "yes" : "no");
Output:
int(15)
string(3) "105"
float(2)
bool(true)
bool(false)
bool(false)
bool(false)
bool(true)
bool(true)
string(2) "no"
string(3) "yes"
The last two lines are the ones to memorise, because they contradict each other in a way that looks like a bug and is not. "0" is falsy: it is the one non-empty string PHP treats as no. "0.0" is truthy, because it is a non-empty string that is not exactly "0". Any code that checks a submitted value with if ($input) has therefore already lost, since a user who types a legitimate zero is indistinguishable from a user who typed nothing. The fix is to say what you mean: if ($input !== "") or if ($input !== null) or, better, run the value through a validator that returns a typed result.
Technical Depth: What A Value Knows About Itself
The complete list of types
PHP has eight storable types and no more. Everything else you will see in a type declaration is a constraint, not a container.
| Type | Written as | What var_dump shows | Worth knowing |
|---|---|---|---|
bool | true, false | bool(true) | the keywords are case-insensitive, so TRUE works and looks dated |
int | 42, 0x2a, 0b101010, 1_000_000 | int(42) | 64-bit on any modern build, and arithmetic that overflows becomes a float rather than wrapping |
float | 0.5, 1.2e3 | float(0.5) | an IEEE 754 double, which is why gettype still calls it double |
string | "Ada", 'Ada' | string(3) "Ada" | a byte string, so the reported length is bytes and not characters |
array | [1, 2], ["k" => 1] | array(2) followed by its contents | one ordered map doing the work of list, dictionary, and record |
object | new stdClass | object(stdClass) plus an id and property count | assigned by handle, so two variables can name one object |
null | null | NULL | the only value of its type, meaning the absence of a value |
resource | fopen("x", "r") | resource(5) of type (stream) | a legacy external handle; new extensions return objects instead |
The words mixed, iterable, callable, void, never, and static appear only in declarations. iterable means an array or a Traversable, callable means something invokable, void and never describe returns rather than values, and none of them is a tag a value can carry.
The falsy list is shorter than people think
| Value | In boolean context |
|---|---|
false | false |
0 and -0 | false |
0.0 and -0.0 | false |
| the empty string | false |
the string "0" | false |
| the empty array | false |
null | false |
everything else, including "0.0", "00", a single space, "false", 0.1, and [0] | true |
Nine entries, and any value not on the list is true. An object is always truthy even with no properties, which is why a null check on an object must be !== null rather than a bare if.
Loose comparison, before and after PHP 8
| Expression | PHP 7 result | PHP 8 result |
|---|---|---|
0 == "foo" | true | false |
0 == "" | true | false |
0 == "0" | true | true |
"abc" == 0 | true | false |
"1" == "01" | true | true |
"10" == "1e1" | true | true |
100 == "1e2" | true | true |
null == 0 | true | true |
"" == null | true | true |
[] == false | true | true |
The PHP 8 rule fits in one sentence and is worth learning verbatim: when a number is compared with a string, PHP checks whether the string is numeric; if it is, both sides are compared as numbers, and if it is not, the number is converted to a string and both sides are compared as text. That is why 100 == "1e2" is still true -- "1e2" is a perfectly good numeric string in scientific notation -- while 0 == "foo" is now false. Rows seven, eight, and nine did not change and still surprise people: null is loosely equal to 0, to the empty string, and to false, which is exactly why isset() and array_key_exists() exist as separate tools.
What strict_types actually changes
| Call | Coercive mode, the default | With strict_types=1 |
|---|---|---|
f(int $n) given the string "7" | accepted, becomes 7 | TypeError |
f(int $n) given 7.0 | accepted, becomes 7 | TypeError |
f(int $n) given 7.5 | accepted as 7, deprecated since 8.1 | TypeError |
f(int $n) given true | accepted, becomes 1 | TypeError |
f(float $x) given 7 | accepted, becomes 7.0 | accepted, the one widening still allowed |
f(string $s) given 42 | accepted, becomes "42" | TypeError |
| a function with a declared return type | the returned value is converted | TypeError |
The detail that catches teams out is where the declaration applies. strict_types is per file and governs the calls made from that file, not the calls made into it. A strict file calling a library gets strict argument checking even if the library never heard of the setting; a coercive file calling your carefully typed function still gets coercion at the boundary. Return types are checked according to the file that contains the function. The practical consequence is that the declaration is worth putting in every single file, because one file without it is a hole in the fence rather than a small inconvenience.
References, and the loop that keeps biting
<?php
declare(strict_types=1);
$a = 1;
$b = &$a;
$b++;
echo "a={$a} b={$b}", PHP_EOL;
$weights = [10, 20, 30];
foreach ($weights as &$w) {
$w *= 2;
}
unset($w);
print_r($weights);
$copy = $weights;
$copy[0] = 999;
echo "original first element: {$weights[0]}", PHP_EOL;
Output:
a=2 b=2
Array
(
[0] => 20
[1] => 40
[2] => 60
)
original first element: 20
$b = &$a makes both names refer to one value, so incrementing either changes both. In foreach ($weights as &$w) the same mechanism lets you modify the array in place, and the unset($w) afterwards is not tidiness -- it is required. Without it $w is still a reference to the final element, and the next innocent-looking foreach ($weights as $w) would overwrite element two on every iteration while you watched. The final three lines show the other half of PHP's assignment rules: arrays are assigned by value with copy-on-write, so $copy is a genuinely separate array and the original keeps its 20. Objects are the exception, assigned by handle, which is why a clone keyword exists at all.
Real World Example: Reading The Weighbridge Log
The hut's log arrives as text, one line per lorry, and text is the only thing PHP ever really receives -- from a form, a query string, a CSV, an API. Everything in this lesson exists to answer one question about that text: how do you turn strings into typed values, once, at the edge, and refuse the ones that are not what they claim?
<?php
declare(strict_types=1);
$log = [
"COPPER, 12500, 620",
"CARDBOARD, 84000, 4",
"ALUMINIUM, 3125, 118",
"STEEL, twelve tonnes, 21",
"BRASS, 4680, ",
"LEAD, 0, 95",
];
$accepted = [];
$rejected = [];
foreach ($log as $offset => $line) {
$lineNo = $offset + 1;
$parts = array_map('trim', explode(",", $line));
if (count($parts) !== 3) {
$rejected[] = ['line' => $lineNo, 'reason' => "wrong field count"];
continue;
}
[$material, $gramsRaw, $penceRaw] = $parts;
$grams = filter_var($gramsRaw, FILTER_VALIDATE_INT);
$pence = filter_var($penceRaw, FILTER_VALIDATE_INT);
if ($grams === false) {
$rejected[] = ['line' => $lineNo, 'reason' => "weight not an integer: [{$gramsRaw}]"];
continue;
}
if ($pence === false) {
$rejected[] = ['line' => $lineNo, 'reason' => "price not an integer: [{$penceRaw}]"];
continue;
}
if ($grams <= 0) {
$rejected[] = ['line' => $lineNo, 'reason' => "weight not positive: [{$grams}]"];
continue;
}
$accepted[] = [
'material' => $material,
'grams' => $grams,
'pence' => $pence,
'value' => intdiv($grams * $pence, 1000),
];
}
$rule = str_repeat("-", 38);
printf("WEIGHBRIDGE LOG -- %d lines read\n", count($log));
echo $rule, "\n";
printf("%-12s %7s %6s %10s\n", "MATERIAL", "GRAMS", "P/KG", "VALUE");
$mass = 0;
$value = 0;
foreach ($accepted as $row) {
$mass += $row['grams'];
$value += $row['value'];
printf("%-12s %7d %6d %10s\n", $row['material'], $row['grams'], $row['pence'], number_format($row['value'] / 100, 2));
}
echo $rule, "\n";
printf("accepted: %d rejected: %d\n", count($accepted), count($rejected));
printf("total mass: %d g\n", $mass);
printf("total value: %s\n", number_format($value / 100, 2));
echo "rejects:\n";
foreach ($rejected as $reject) {
printf(" line %d: %s\n", $reject['line'], $reject['reason']);
}
Output:
WEIGHBRIDGE LOG -- 6 lines read
--------------------------------------
MATERIAL GRAMS P/KG VALUE
COPPER 12500 620 77.50
CARDBOARD 84000 4 3.36
ALUMINIUM 3125 118 3.68
--------------------------------------
accepted: 3 rejected: 3
total mass: 99625 g
total value: 84.54
rejects:
line 4: weight not an integer: [twelve tonnes]
line 5: price not an integer: []
line 6: weight not positive: [0]
The whole program turns on one comparison, and it is the reason this lesson spent so long on == versus ===. filter_var returns the converted integer on success and false on failure, so a valid weight of zero and an invalid weight of "twelve tonnes" both look like no under a loose test. if (!$grams) would reject line six for the wrong reason and would reject a legitimate zero-gram reading identically. if ($grams === false) asks the only question that distinguishes them: is this literally the boolean false, rather than something that merely behaves like it? Every validator in PHP's standard library has this shape -- strpos returning 0 for a match at the start of a string is the same trap wearing a different hat -- and === is the whole answer.
Notice where types change and where they do not. explode produces an array of strings, trim returns strings, and every value stays a string until filter_var converts it deliberately. After that line, $grams and $pence are integers and stay integers: intdiv($grams * $pence, 1000) never touches a float, so a value of 368.75 pence becomes 368 by an explicit rule you can read, rather than by whatever round felt like doing. That is the boundary pattern in miniature. Text arrives, one gate converts and rejects, and behind the gate the program works in real types with real names.
The rejects list is the part beginners leave out and operations teams beg for. Three lines out of six were bad, each in a different way, and the program says which line and what was wrong with it -- including the raw text in square brackets, so an empty field is visibly empty rather than mysteriously absent. Silently skipping bad rows makes a program that always succeeds and quietly under-reports the day's takings by a third, which is worse than one that crashes. Note also that $offset comes from foreach and is zero-based, so $lineNo adds one: a human reading the log counts from one, and an off-by-one in an error message costs somebody ten minutes of staring at the wrong row.
The design flaws are real and worth naming. explode(",", $line) is not a CSV parser: a material called "BRASS, YELLOW" in quotes would be split down the middle and rejected as having four fields, and PHP ships str_getcsv precisely for this. The reject reasons are strings assembled for a human, so nothing downstream can group by cause or count "bad weight" errors without parsing English again -- an enum or an error code belongs there. intdiv truncates, which silently favours the scrapyard by up to a penny per load, and nobody in the code ever said that was the intended commercial rule. And the totals are accumulated in PHP integers, which is fine until a busy month, because $mass overflowing PHP_INT_MAX would turn into a float and start losing precision without a single warning. Two lesser rough edges: the log is a hardcoded array rather than a stream, so a real file of a million lines would be read entirely into memory, and filter_var accepts leading plus signs and surrounding whitespace, so "+12500" is quietly valid input nobody planned for.
Common Mistakes
- Testing whether something was submitted with
if ($value). The falsy list includes0,"0", and the empty string, so a customer who legitimately typed zero is indistinguishable from one who typed nothing. Ask the precise question instead:isset($_POST['qty'])for presence,array_key_existswhen the value may legitimately be null, and!== ""for emptiness. - Comparing a validator result loosely.
filter_varreturnsfalseon failure and0on the input"0";strposreturnsfalsewhen not found and0when found at the start.if (!$result)conflates the two and produces a bug that only appears for the first character or for a genuine zero. Always=== false. - Omitting
unset()after a by-referenceforeach. The loop variable survives the loop as a live reference to the last element, so the next ordinaryforeachover the same array overwrites that element on every iteration. The symptom is a final row that mysteriously equals the second-to-last, and it has cost people entire afternoons. - Believing PHP 8 fixed
==. Only number-to-string comparison changed.null == 0,"" == null,[] == false, and"1" == "01"are all still true, and"1e3" == "1000"still surprises people who thought exponent strings were text. - Trusting
is_numericto mean "an integer I can use". It accepts"12.5","1e5","+12", and leading whitespace, all of which are numeric and none of which is an integer. When you need digits usectype_digit, and when you need a converted integer usefilter_varwithFILTER_VALIDATE_INT. - Comparing
gettype()against the words you write in declarations. It returns"double","integer", and"boolean", sogettype($x) === "float"is never true and the branch silently never runs.get_debug_type()returnsfloat,int,bool, and real class names, which is what you want in both comparisons and error messages. - Expecting a function to see the variables around it. PHP does not capture enclosing scope implicitly: inside a function body only the parameters, the function's own locals, and the superglobals exist. The three deliberate doors are the
globalkeyword, a closure'suseclause, andstaticfor a local that survives calls -- and reaching forglobalis almost always the wrong one. - Comparing floats with
===.0.1 + 0.2 === 0.3is false, and so is any comparison that assumes decimal fractions survive a round trip through binary. Compare with a tolerance, such asabs($a - $b) < 0.00001, or move the quantity into integers and stop comparing floats at all. - Assuming an integer stays an integer, or that array keys keep their type.
PHP_INT_MAX + 1silently becomes a float and starts losing precision, and$a["7"] = "x"stores the key as the integer7, soarray_keys($a)[0] === "7"is false and every strict comparison against the key you thought you wrote fails. Numeric-looking string keys are normalised to integers, and no warning is issued.
Best Practices
- Declare strict types in every file, without exception. One file missing the line is a gap in the fence rather than a small inconvenience, because the setting governs the calls made from that file. Add it to your editor's file template so you never have to remember.
- Convert at the boundary and trust your types afterwards. One gate turns request data, file rows, and API payloads into integers, floats, enums, and value objects; behind that gate no function should be re-checking whether a quantity might be a string. Validation everywhere is the same as validation nowhere.
- Default to
===and!==. Make loose comparison the exception, and when you do use it, write a short comment naming the conversion you are relying on. Code review can then check that the conversion is the one you meant. - Use
get_debug_type()for messages andvar_dump()for exploring.var_export()gives you output you can paste back into code, andprint_r()is easiest to read for nested arrays. Reservegettype()for legacy code that already depends on its old vocabulary. - Put the types in the signature. Parameter types, return types, and typed properties turn a comment nobody trusts into a rule the engine enforces, and they are the single cheapest improvement available to an untyped codebase.
- Reach for
??and??=instead ofisset()ladders.$page = (int) ($_GET['page'] ?? 1);states the default and the target type in one readable line, and??is null-safe rather than falsy-safe, so a legitimate zero survives. - Avoid references unless an API requires them.
&makes two names for one value, which reads fine on the line where it is written and terribly three functions away. Returning a new value is almost always clearer, and PHP's copy-on-write means it is usually not slower either. - Put the unit in the name and keep the quantity whole.
$grams,$pence,$timeoutMscannot be confused with kilograms, pounds, or seconds, and integers of the smallest unit never drift the way floats do. Every one of the reconciliation bugs in a billing system starts with a variable called$amount.
Practice Exercises
- Build the falsy table yourself. Put twelve values in an array -- including
0,"0","0.0","00", a single space, the empty string,0.0,[],[0],null,"false", andnew stdClass()-- then print three aligned columns:var_exportof the value,get_debug_type, and the boolean cast. Compare your table with the one in this lesson and write down the two rows you would have guessed wrongly. - Reproduce the PHP 8 comparison change. Put all ten expressions from the comparison table into a script and print each result. For every row where PHP 8 differs from PHP 7, write one sentence naming which side was converted and to what. Then find one place in code you have written where the old behaviour would have been a security bug rather than a curiosity.
- Harden the weighbridge reader. Replace
explodewithstr_getcsvand add a row whose material is a quoted"BRASS, YELLOW". Replace the English reject reasons with a small set of codes and print a count per code. Finally, decide out loud whether truncation or half-up rounding is the commercial rule, and implement the one you chose with integer arithmetic only. - Break the reference loop on purpose. Double an array of five numbers with
foreach ($a as &$v), deliberately omit theunset($v), then loop over the same array again by value and print it withprint_r. Explain the result you get, add theunset, and confirm the difference. Keep the broken version in a comment as a reminder.