Data Types and Casting
Every PHP value has a type such as int, float, string, bool, array or null, and casts and operators convert between types by fixed rules, which is why strict === comparison is safer than ==.
Inspect conversions before relying on an input as a number or boolean.
A Pageturn order form sends the quantity "2" as text, and the stock count is the number 3. Is "2" less than 3? Can you add them? PHP's answer depends on its types and on the rules it uses to turn one type into another. Knowing those rules lets you predict results instead of hoping.
The rule
Every value has a type; a cast converts it, and conversion follows fixed rules.
PHP's main types:
| Group | Types | Pageturn example |
|---|---|---|
| Scalar | int, float, string, bool |
3, 9.99, "Dune", true |
| Compound | array, object |
["Dune", "Emma"] |
| Special | null |
a book with no subtitle |
var_dump($x) shows a value with its type, and get_debug_type($x) returns the type name, such as "float".
Casting means converting on purpose: (int), (float), (string), (bool), (array).
<?php
var_dump((int) "2"); // int(2)
var_dump((int) "12abc"); // int(12) reads leading digits
var_dump((int) "abc"); // int(0)
var_dump((int) 9.99); // int(9) cuts off, never rounds
var_dump((string) 9.99); // string(4) "9.99"
var_dump((bool) "0"); // bool(false)The false list. Converted to bool, only these are false: false, 0, 0.0, "", "0", [] and null. Everything else is true, including "0.0", "false" and " ".
PHP also converts automatically when an operator needs it. "2" + 3 is 5, because + wants numbers; "2" . 3 is "23", because . wants strings. In PHP 8, a string with no number at all, as in "abc" + 1, throws a TypeError.
Comparisons follow the same idea. == converts before comparing, so "3" == 3 is true. === compares type and value, so "3" === 3 is false. Prefer === unless you mean to convert.