Type Juggling, Coercion and Casting

7.Type Juggling, Coercion and Casting

M

In this chapter

We'll learn exactly how PHP converts values from one type to another — automatically (type juggling) and on purpose (casting) — which strings count as numbers, what each value becomes as a bool, and why "false" == true gave away a free booking.

15–17 min

The Problem in Real Life

Back to the bug that started this Act. Mia writes the partner's booking out by hand: price "25 USD", paid "false". Then two lines of her own code: $price * 2 and if ($paid == true).

"PHP did two conversions here without asking," says Marcus. "It turned "25 USD" into a number, and "false" into a bool. Both conversions follow rules. Once you know the rules, you'll never be surprised by them again — and you'll know when to convert values yourself."

M

How can the text "false" be true?

Mia

Converting by Accident vs. Converting on Purpose

Silent conversions

Calculations, if checks and == comparisons all convert values without asking.

Surprising rules

"false" is true, "0" is false, and "25 USD" is 25 — if you don't know why.

Converting on purpose

Casts like (int) convert exactly when you decide — but they never complain.

Type Juggling, Coercion and Casting

Three words for converting: PHP converts values between types in three situations, and each has a name:

  • Type juggling: PHP converts automatically because of what you're doing — maths needs numbers, joining text needs strings, if needs a bool, == needs two comparable values. Also called implicit conversion.
  • Coercion: PHP converts a value passed to a typed function parameter, in the default (non-strict) mode — Act 02, chapter 6.
  • Casting: you convert a value on purpose, by writing the target type in brackets: (int) $price. Also called explicit conversion.

Juggling in maths — numeric strings: for +, -, * and /, PHP needs numbers. Strings are converted by these rules. A numeric string — one that's entirely a number, like "25", "12.5", "1e3" or " 25" (spaces around are allowed) — is converted cleanly. A leading-numeric string, which starts with a number and then has other text, like "25 USD", is converted using just the number at the start — with a warning. A string with no number at the start, like "abc", can't be used at all: PHP throws a TypeError. That's Mia's first bug: "25 USD" * 2 gave 50 and a warning that nobody read.

Numeric, leading-numeric and non-numeric strings in maths
<?php
var_dump("25" * 2); // int(50): numeric, clean
var_dump("12.5" + 1); // float(13.5): numeric, clean
var_dump("25 USD" * 2); // int(50) — with a warning
var_dump("abc" * 2); // TypeError: Unsupported operand types: string * int
What PHP says
int(50)
float(13.5)
Warning: A non-numeric value encountered in main.php on line 5
int(50)
Fatal error: Uncaught TypeError: Unsupported operand types: string * int in main.php:6

Juggling to string: echo and the . operator need text, so other types are converted to strings: 25 becomes "25", 12.5 becomes "12.5", true becomes "1", and false and null become empty text (Act 02, chapter 5). That's why "10" . 5 is "105" while "10" + 5 is 15 — the operator decides the conversion.

The operator decides the conversion
<?php
var_dump("10" + 5); // int(15): + needs numbers
var_dump("10" . 5); // string(3) "105": . needs text

Juggling to bool: if (Act 06) needs a bool, so other types are converted. Only a few values become false — the same "empty-like" values as empty() in Act 03: 0, 0.0, "", "0", null and []. Everything else is true, including " ", "0.0", -1, [0] — and the text "false". PHP doesn't read the word; it only sees a non-empty string. That's Mia's second bug.

Mia's second bug: "false" is true
<?php
$paid = "false"; // from the partner, as text
if ($paid == true) {
echo "Booking confirmed\n"; // printed!
}
var_dump((bool) "false"); // bool(true)
var_dump((bool) "0"); // bool(false)
var_dump((bool) " "); // bool(true)
var_dump((bool) [0]); // bool(true): a list with one item

Juggling in == comparisons: == ("loosely equal") converts values before comparing, when their types differ. Some results are reasonable — "25" == 25 is true. Others are traps: "false" == true is true (the string is converted to a bool), null == false is true, and "10" == "1e1" is true (both are numeric strings, so they're compared as numbers). PHP 8 fixed the worst one: "abc" == 0 used to be true and is now false. The cure is the strict comparison ===, which never converts: the values must have the same type and the same value. Act 05 covers both in depth; from today, prefer ===. The table below collects the surprises.

Table — == surprises (all from PHP 8.5)
ComparisonResultWhy
"25" == 25trueThe numeric string is compared as a number
"false" == truetrueAny non-empty string except "0" is true
null == falsetruenull converts to false
"10" == "1e1"trueBoth are numeric strings: 10 and 10
"abc" == 0falsePHP 8: compared as strings (was true before PHP 8)
"25 USD" == 25falseNot fully numeric, so compared as strings
"25" === 25false=== never converts: string vs. int
=== never converts
<?php
$paid = "false";
var_dump($paid == true); // bool(true): converted, wrong
var_dump($paid === true); // bool(false): a string is never the bool true
var_dump($paid === "true"); // bool(false): the honest check for this data

Casting — converting on purpose: to convert yourself, put the type in brackets before the value: (int), (float), (string), (bool) or (array). The functions intval(), floatval(), strval() and boolval() do the same. Casting follows the same rules as juggling, with one big difference: casting never warns and never fails. (int) "25 USD" is silently 25, (int) "USD 25" is silently 0, and (int) 12.9 is 12 — the decimals are cut off, not rounded. The table below shows common results.

Table — Common casts
CastResultNote
(int) "25"25Clean
(int) "25 USD"25No warning — the rest is ignored
(int) "USD 25"0No warning — no number at the start
(int) 12.912Cut off, not rounded
(float) "12.50"12.5Clean
(string) false""Empty text
(bool) "0"falseOne of the few false strings
(bool) "false"trueA non-empty string
(array) "Tom"["Tom"]Wrapped in a one-item list
Casting never warns
<?php
var_dump((int) "25 USD"); // int(25)
var_dump((int) "USD 25"); // int(0): a silent zero
var_dump((int) 12.9); // int(12): cut off
var_dump(intval("42")); // int(42)
var_dump((string) 25); // string(2) "25"

No warnings at all — which is exactly why casting is not a way to check data.

When to cast, and when not to: casting is the right tool when you already know the value is valid — for example, after checking it (chapter 8). It's the wrong tool for checking: (int) "USD 25" doesn't tell you anything went wrong, it just gives you 0, and a price of 0 is how a free haircut happens. So the order is always: check first, then convert, then pass the value to typed functions. For the partner booking, that means: check that the price is a whole number, convert it, and compare paid with === "true" — never with == true.

Key Takeaway

PHP converts types automatically (juggling) in maths, string joins, if conditions and == comparisons; for typed parameters in non-strict mode (coercion); and when you cast with (int), (string) and so on. Leading-numeric strings like "25 USD" juggle with a warning, non-numeric ones throw. Only 0, 0.0, "", "0", null and [] are false — "false" is true. Casts never warn, so check values first, then cast, and compare with ===.

Why This Matters

Type juggling is the source of some of PHP's most famous bugs — and most of them come from data that arrives as text, which at BookBay is almost all of it. Knowing the rules turns "PHP is weird" into "of course: a non-empty string is true".

It also sets Mia's habit for the rest of the course: compare with ===, check outside data before using it, cast only values you've already checked, and let typed functions reject everything else loudly.

Mia rewrites the paid check as $paid === "true". But the price still worries her. "I can't cast "25 USD", because casting never complains. So how do I ask PHP whether a value is a proper number before I convert it?" That's the last chapter of this Act.