PHP Data Types
PHP data types describe what kind of value a variable holds. PHP decides the type automatically, but knowing the types helps you avoid bugs and write typed functions in PHP 8.
The Main PHP Data Types
- string: text like "hello"
- int: whole numbers like 42 or -7
- float: decimals like 3.14
- bool: true or false
- array: an ordered map of values
- object: an instance of a class
- null: no value
- Enums (PHP 8.1+): a fixed set of named cases
Inspecting Types With var_dump
var_dump() prints the type and value. It is the most useful debugging tool for beginners.
<?php
var_dump("PHP");
var_dump(8);
var_dump(8.3);
var_dump(true);
var_dump(null);
var_dump([1, 2]);string(3) "PHP"
int(8)
float(8.3)
bool(true)
NULL
array(2) {
[0]=>
int(1)
[1]=>
int(2)
}Type Casting
You can convert a value to another type by putting the type in parentheses. Functions like intval() do the same thing.
<?php
$input = "42 apples";
$n = (int) $input;
echo gettype($n), " ", $n, "\n";
echo (string) 3.5 . "\n";
var_dump((bool) "");
var_dump((bool) "0");integer 42 3.5 bool(false) bool(false)
Falsy Values
When converted to bool, these values become false: false, 0, 0.0, "", "0", an empty array and null. Everything else is true. This matters a lot in if statements.
PHP Enums
Enums let you define a type with a limited set of values, perfect for statuses. Backed enums carry a string or int value.
<?php
enum Status: string {
case Draft = 'draft';
case Published = 'published';
}
$s = Status::from('published');
echo $s->name . " => " . $s->value;Published => published
Frequently asked questions
How do I check the type of a variable in PHP?
Use gettype() for a name, get_debug_type() for a modern readable name, or functions like is_int(), is_string() and is_array() for checks.
Is PHP strongly typed?
PHP is dynamically typed, but PHP 8 supports type declarations and strict_types mode, so you can make it behave much like a strongly typed language.
What is the difference between null and an empty string?
null means no value at all, while "" is a string with zero characters. Both are falsy, but is_null() is only true for null.