4 min read
Type Juggling & Casting
Prerequisites: Variables & data types
PHP automatically converts ("juggles") types in many operations — convenient, but a frequent source of subtle bugs if you're not watching for it.
$total = "5" + 3; // 8 — the string "5" is juggled to an int
$label = "Total: " . 5; // "Total: 5" — . concatenates, converting 5 to a string
$count = (int) "42abc"; // 42 — casts up to the first non-numeric character
$flag = (bool) ""; // false — empty string is "falsy"
Common mistakes
- Using
==(loose comparison), which juggles types before comparing:0 == "abc"wastruein PHP before 8.0. Prefer===(covered next, in Operators) to avoid this entirely.