Every value in PHP has a type. The type decides what you can do with the value. You can add two numbers, but adding two names makes no sense.
PHP has these main types:
| Type | Example | Used for |
|---|---|---|
string | "Hello" | Text |
int | 42 | Whole numbers |
float | 3.14 | Numbers with decimals |
bool | true | Yes or no |
array | [1, 2, 3] | A list of values |
object | new User() | An instance of a class |
null | null | No value |
resource | fopen(...) | A handle to something outside PHP, like a file |
Looking at a value: var_dump()
var_dump() prints the type and the value. It is the most useful debugging tool for a beginner.
<?php
var_dump("Hello");
var_dump(42);
var_dump(3.14);
var_dump(true);
var_dump(null);
string(5) "Hello"
int(42)
float(3.14)
bool(true)
NULL
string(5) means a string with 5 characters.
Just the type name: gettype()
<?php
echo gettype("Hello") . "\n";
echo gettype(42) . "\n";
echo gettype(3.14) . "\n";
echo gettype([1, 2]) . "\n";
string
integer
double
array
gettype() has old names (“integer”, “double”). A newer function, get_debug_type(), uses the names you write in code (int, float).
<?php
echo get_debug_type(42) . "\n";
echo get_debug_type(3.14) . "\n";
echo get_debug_type(null);
int
float
null
Variables do not have types, values do
A PHP variable can hold any type, and it can change.
<?php
$data = 5;
var_dump($data);
$data = "five";
var_dump($data);
int(5)
string(4) "five"
The next lessons look at each type in turn.
Use var_dump() while you learn
var_dump(). You will often discover that a “number” is really a string.