PHP Data Types
PHP Data Types: Scalar, Compound, and Special Values
Every value stored in a PHP variable belongs to a specific data type that dictates how PHP stores it and which operations are valid. PHP groups its types into four scalar types, compound types like arrays and objects, and special types like null and resource.
Core PHP Type Categories
Knowing what type a variable holds prevents subtle comparison and math bugs.
| Category | Type | Example Value | Purpose |
|---|---|---|---|
| Scalar | string |
"Hello PHP" |
Text sequences |
| Scalar | int |
42 |
Whole numbers |
| Scalar | float |
19.99 |
Decimal numbers |
| Scalar | bool |
true / false |
Logical flags |
| Compound | array |
['a', 'b'] |
Ordered maps and lists |
| Compound | object |
new DateTime() |
Class instances |
| Special | null |
null |
Intentional empty value |
Use var_dump() or get_debug_type() during debugging to inspect both the exact type and value of any variable.
<?php
declare(strict_types=1);
$title = "PHP Guide";
$lessonNumber = 7;
$rating = 4.9;
$published = true;
$tags = ["php", "backend", "web"];
$deletedAt = null;
var_dump($title, $lessonNumber, $rating, $published, $tags, $deletedAt);
echo "Detected type: " . get_debug_type($tags) . PHP_EOL;
Type Juggling vs Strict Types
By default, PHP automatically converts compatible types when needed—for instance, turning "10" into 10 during addition. Adding declare(strict_types=1); at the top of your file stops silent type conversions on function calls.
<?php
declare(strict_types=1);
function addTax(float $price, float $rate): float
{
return $price * (1 + $rate);
}
echo addTax(100.0, 0.15) . PHP_EOL;
Common Mistakes to Avoid
- Confusing
empty()withnullchecks:empty(0)andempty("0")returntrue. Use$value === nulloris_null()when checking specifically fornull. - Comparing floats with
===without rounding: Binary floating-point math can produce0.30000000000000004. Store money as integer cents or useround(). - Using
gettype()instead ofget_debug_type():gettype()returns legacy names like"double"instead of"float";get_debug_type()returns modern PHP 8 type names.
Frequently Asked Questions
What is the difference between NULL and an empty string ""?
null represents the absence of any value, whereas "" is a valid string of length zero.
Can a PHP variable change its type after assignment?
Yes. PHP is dynamically typed, so assigning 42 to $x and later "forty-two" to $x is valid, unless constrained by a typed class property.
How do I safely check if a value is an integer string from a form?
Use filter_var($input, FILTER_VALIDATE_INT) !== false rather than is_int(), because HTML form inputs always arrive as strings.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.