The previous lesson showed PHP converting types automatically. Type casting is doing that conversion yourself, on purpose, so the result is predictable rather than left to PHP's own rules.
Put the target type in parentheses in front of a value to cast it:
<?php
$price = "19.99";
$number = (float) $price; // 19.99 as an actual float
$whole = (int) $price; // 19 (int cast truncates, doesn't round)
$text = (string) 42; // "42"
$flag = (bool) 1; // true
?>Note that casting to int truncates rather than rounds — (int) 19.99 gives 19, not 20. Use round() first if you actually need rounding.
PHP also provides named functions that do the same job and read a little more clearly in context:
<?php
$n = intval("42abc"); // 42 — reads leading digits, ignores the rest
$f = floatval("3.14"); // 3.14
$s = strval(100); // "100"
?>Casting anything to bool follows a specific set of rules worth memorizing, since PHP applies this same logic inside every if statement:
| Value | Casts to bool as |
|---|---|
| 0, 0.0, "0" | false |
| "" (empty string) | false |
| [] (empty array) | false |
| null | false |
| Any other number or non-empty string | true |
The "0" vs "0.0" trap
The string "0" is falsy, but the string "0.0" is truthy — it's a non-empty string that just happens to contain the characters "0.0". This exact gotcha has caused real bugs in real PHP code; when in doubt, compare explicitly ($value === "0") rather than relying on truthiness.