iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

TypeExample
string'Hello' / "Hi $name"
int42, -7, 0xff (hex)
float3.14, 2.5e3
booltrue, false
array[1, 2, 3] or ['a' => 1]
objectnew User()
callablefn($x) => $x*2, 'strlen'
iterableArray or Traversable.
nullnull — "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

TestMeans
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

Example
<?php
var_dump(1, 1.5, 'hi', true, null, [1, 2], (object) ['x' => 1]);
Try it Yourself »

Exercise

Strict equality operator is…

if ($a $b) {}

Test yourself

Q1. Which is NOT a primitive type?
Q2. "1" === 1 evaluates to…
Q3. A safer null check is…

Discussion

Loading…