PHP Data Types
PHP has eight primitive types and a few special ones. Most code uses just five — string, int, float, bool, and array.
The set
| Type | Example |
|---|---|
string | 'Hello' / "Hi $name" |
int | 42, -7, 0xff (hex) |
float | 3.14, 2.5e3 |
bool | true, false |
array | [1, 2, 3] or ['a' => 1] |
object | new User() |
callable | fn($x) => $x*2, 'strlen' |
iterable | Array or Traversable. |
null | null — "no value". |
mixed (8.0+) | Any type — escape hatch. |
Inspect at runtime
PHP
var_dump(1); // int(1)
var_dump('hi'); // string(2) "hi"
var_dump([1, 2]); // array(2) {[0]=> int(1), [1]=> int(2)}
echo gettype($x); // string name of the type
get_debug_type($x); // better — works for objects too
Loose comparison gotchas
PHP used to compare across types automatically — and the results were famously surprising. PHP 8 tightened things up, but the rule is still: use === unless you really want type juggling.
PHP
var_dump('1' == 1); // true (loose)
var_dump('1' === 1); // false (strict)
var_dump(0 == 'abc'); // false in PHP 8 (was true before)
null vs empty vs isset
| Test | Means |
|---|---|
isset($x) | Defined AND not null. |
empty($x) | Not set, or one of: 0, '0', '', null, false, []. |
is_null($x) | Strict null check. |
Tip: Declare types on properties and parameters. PHP enforces them at runtime, and your IDE finally knows what's going on.
Example
Exercise
Strict equality operator is…
if ($a
$b) {}
Three characters.
Discussion
Loading…