Data Types and Casting
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.
The shortcut
Ask "which type does this operator or cast want?" and apply that type's rule.
The input
$qty = $_POST['qty'];holds the string"2". Form data always arrives as strings.
The trap is trusting a cast to validate. (int) "abc" quietly gives 0, which looks like a real quantity. Check the input first; the section on HTTP shows how.
Drills
Answer fast — trust the rule.
What is (int) 7.8?
Which value becomes true when cast to bool?
What is "4" . 2?
Which comparison is false?
What does get_debug_type(9.99) return?
Remember
- Every value has a type; casts and operators convert using fixed rules.
- Shortcut: ask which type the operator wants, then apply its rule.
- Trap: casting does not validate —
(int) "abc"is0— and==converts while===does not.
