PHP Data Types
What Is a Data Type?
In simple terms: A data type describes what kind of value something is — a whole number, a decimal number, text, true/false, a list, and so on.
Technically: Every value in PHP has a type that determines how it is stored in memory, which operations can be performed on it, and how it behaves when compared or converted. Variables themselves do not have fixed types; the value they hold does.
Why Data Types Matter
The same-looking data behaves differently depending on its type:
<?php
var_dump(10 + 5); // int(15) — numeric addition
var_dump("10" . "5"); // string(3) "105" — text joined together
var_dump(7 / 2); // float(3.5) — division can produce a decimal
var_dump("abc" == 0); // bool(false) — comparison rules depend on types
Understanding types explains why a calculation returns a decimal, why a comparison is true or false, why a function rejects an argument, and why data from forms and databases sometimes behaves unexpectedly.
PHP's Type Categories
PHP has ten basic value types, grouped into three categories.
| Category | Type | Example | Holds |
|---|---|---|---|
| Scalar (single value) | bool | true, false | A truth value |
int | 42, -7, 0x1F | Whole numbers | |
float | 3.14, 1.5e3 | Decimal numbers | |
string | "Hello", 'PHP' | Text (a sequence of bytes) | |
| Compound (contain other values) | array | [1, 2, 3], ['name' => 'Asha'] | Ordered key–value collections |
object | new DateTime() | Instances of classes, with properties and methods | |
callable | 'strtoupper', fn($x) => $x * 2 | Anything that can be called like a function | |
iterable | Arrays, generators | Anything usable in foreach | |
| Special | null | null | No value |
resource | fopen('file.txt', 'r') | A handle to an external resource |
Strictly speaking, callable and iterable describe capabilities that some values have rather than separate storage types. A callable is often a string, array, or Closure object; an iterable is an array or an object implementing Traversable. They appear in this list because they can be used in type declarations.
For type declarations, PHP also provides mixed (any type), void (function returns nothing), never (function never returns), and static/self for classes. These are covered in the Type Declarations in Functions and Mixed and Never Types lessons.
Dynamic Typing
PHP is dynamically typed: you never declare a variable's type, and PHP determines it from the assigned value.
<?php
$data = 100; // int
$data = "one hundred"; // now string
$data = [1, 0, 0]; // now array
Advantages
- Less code to write, and fast prototyping.
- Easy handling of loosely structured data such as form input, which always arrives as strings.
Disadvantages
- Type-related bugs appear only when the code runs.
- PHP sometimes converts types automatically (type juggling), which can produce surprising results.
Modern PHP reduces these risks with type declarations on function parameters, return values, and properties, and optionally with strict types:
<?php
declare(strict_types=1);
function addTax(float $amount): float
{
return $amount * 1.18;
}
echo addTax(1000); // 1180
echo addTax("1000"); // TypeError in strict mode
Variables stay dynamic, but function boundaries become type-checked. Type juggling and strict types have their own lessons.
Inspecting Types
PHP provides several tools to discover a value's type.
Example
<?php
$values = [42, 3.5, "PHP", true, null, [1, 2], new DateTime()];
foreach ($values as $value) {
printf("%-10s %-10s\n", gettype($value), get_debug_type($value));
}
Output
integer int
double float
string string
boolean bool
NULL null
array array
object DateTime
Which Function to Use
| Function | Returns | Notes |
|---|---|---|
var_dump($v) | Prints type and value | Best for debugging |
gettype($v) | "integer", "double", "boolean", "NULL", … | Older function; uses historical names (double for float) |
get_debug_type($v) | "int", "float", "bool", "null", class name | PHP 8.0+. Uses the same names as type declarations and shows the class name for objects. Preferred for error messages. |
is_int(), is_string(), is_array(), … | true / false | Best for checking a type in code |
Type-Checking Functions
<?php
$input = "42";
var_dump(is_string($input)); // bool(true)
var_dump(is_int($input)); // bool(false)
var_dump(is_numeric($input)); // bool(true)
is_int("42")isfalsebecause the value is a string that contains digits.is_numeric("42")istruebecause it checks whether the value looks like a number (an int, a float, or a numeric string).
This distinction is essential when handling form data and URL parameters, which always arrive as strings.
Boolean (bool)
A boolean has only two values: true or false. Booleans represent yes/no states and are the result of comparisons.
<?php
$isPublished = true;
$hasStock = 5 > 0;
var_dump($isPublished, $hasStock);
Output
bool(true)
bool(true)
Many values convert to false in conditions (0, "", "0", [], null). These conversion rules are covered in PHP Booleans.
Integer (int)
An integer is a whole number without a decimal part, positive or negative.
<?php
$quantity = 25;
$temperature = -4;
$hexColor = 0xFF; // hexadecimal = 255
$permissions = 0o755; // octal (PHP 8.1+ prefix) = 493
$flags = 0b1010; // binary = 10
$population = 1_400_000_000; // underscores for readability (PHP 7.4+)
var_dump($hexColor, $permissions, $flags, $population);
echo PHP_INT_MAX;
Output
int(255)
int(493)
int(10)
int(1400000000)
9223372036854775807
- Integers can be written in decimal, hexadecimal (
0x), octal (0or0o), and binary (0b). They are all stored the same way. - Underscores in numeric literals are ignored by PHP and make large numbers easier to read.
- On 64-bit systems, integers range from
PHP_INT_MINtoPHP_INT_MAX(about ±9.2 quintillion). If a calculation exceeds this, the result becomes a float, losing precision.
Details are covered in PHP Numbers.
Float (float)
A float (floating-point number, sometimes called a double) is a number with a decimal part or in exponential notation.
<?php
$price = 499.99;
$rate = 1.5e-3; // 0.0015
$ratio = 10 / 4;
var_dump($price, $rate, $ratio);
var_dump(0.1 + 0.2 == 0.3);
Output
float(499.99)
float(0.0015)
float(2.5)
bool(false)
Why 0.1 + 0.2 == 0.3 Is False
Floats are stored in binary using the IEEE 754 standard. Many decimal fractions, such as 0.1, cannot be represented exactly in binary, just as 1/3 cannot be written exactly in decimal. The tiny rounding errors make 0.1 + 0.2 equal to 0.30000000000000004.
Practical consequence: never compare floats with ==, and avoid floats for money. Store amounts as integers in the smallest unit (paise, cents) or use the BCMath extension. See PHP Floats.
String (string)
A string is a sequence of characters — technically, a sequence of bytes.
<?php
$name = 'Kavitha';
$greeting = "Hello, $name!";
$tamil = "வணக்கம்";
var_dump($greeting);
var_dump(strlen($tamil), mb_strlen($tamil));
Output
string(15) "Hello, Kavitha!"
int(21)
int(7)
- Single-quoted strings are literal; double-quoted strings interpolate variables and escape sequences.
strlen()counts bytes. Tamil characters take 3 bytes each in UTF-8, so the 7-character word occupies 21 bytes.mb_strlen()counts characters. Always use themb_*functions for text that may contain non-English characters.
Strings are covered extensively in the string lessons, starting with PHP Strings.
Array (array)
An array stores multiple values under keys. PHP arrays are ordered maps: they work as lists (numeric keys) and as dictionaries (string keys) at the same time.
<?php
$languages = ["PHP", "Python", "Go"]; // indexed array
$user = ["name" => "Arun", "age" => 28]; // associative array
echo $languages[0] . "\n";
echo $user["name"] . "\n";
var_dump(count($languages));
Output
PHP
Arun
int(3)
Arrays are the most frequently used compound type in PHP: database rows, configuration, JSON data, and form input all appear as arrays. They are covered in the PHP Arrays section.
Object (object)
An object is an instance of a class. A class defines the structure (properties) and behavior (methods); objects are concrete values created from it.
<?php
class Product
{
public function __construct(
public string $name,
public float $price,
) {}
public function priceWithTax(): float
{
return round($this->price * 1.18, 2);
}
}
$lamp = new Product("Desk Lamp", 999.0);
echo $lamp->name . "\n";
echo $lamp->priceWithTax() . "\n";
var_dump($lamp instanceof Product);
Output
Desk Lamp
1178.82
bool(true)
new Product(...)creates an object.->accesses properties and methods.instanceofchecks whether a value is an object of a given class.
Objects let you group data with the code that operates on it. They are covered in the PHP OOP section. PHP also has built-in classes, such as DateTime, PDO, and Exception.
Callable (callable)
A callable is any value that can be called as a function.
<?php
$double = fn(int $n): int => $n * 2;
$numbers = [1, 2, 3];
print_r(array_map($double, $numbers));
print_r(array_map('strtoupper', ['a', 'b']));
var_dump(is_callable($double));
Output
Array
(
[0] => 2
[1] => 4
[2] => 6
)
Array
(
[0] => A
[1] => B
)
bool(true)
Callables let you pass behavior into functions such as array_map(), usort(), and event handlers. See PHP Callback Functions and Anonymous Functions.
NULL (null)
null represents "no value". A variable is null if it was assigned null, if it was unset, or if it was never assigned (which also raises a warning).
<?php
$middleName = null;
var_dump($middleName);
var_dump(is_null($middleName));
echo $middleName ?? "No middle name";
Output
NULL
bool(true)
No middle name
The ?? (null coalescing) operator returns the right side when the left is null or undefined. See PHP NULL.
Resource (resource)
A resource is a special handle to something outside PHP — an open file, a network stream, or a process.
<?php
$handle = fopen('php://memory', 'r+');
var_dump($handle);
echo get_debug_type($handle) . "\n";
fclose($handle);
Output
resource(5) of type (stream)
resource (stream)
(The resource number varies.)
php://memoryis a temporary in-memory stream, used here so the example needs no real file.- Resources should be released when no longer needed (
fclose()); PHP also releases them at the end of the request.
Version note: PHP is gradually replacing resources with objects. Since PHP 8.0, for example,
curl_init()returns aCurlHandleobject andimagecreate()returns aGdImageobject instead of resources. File streams fromfopen()are still resources.
How Types Affect Behavior: A Comparison
<?php
$a = "5";
$b = 5;
var_dump($a == $b); // compares values after conversion
var_dump($a === $b); // compares values and types
var_dump($a + $b); // arithmetic converts "5" to a number
var_dump($a . $b); // concatenation converts 5 to a string
Output
bool(true)
bool(false)
int(10)
string(2) "55"
Explanation
==(loose equality) converts the values to a common type before comparing, so"5"equals5.===(strict equality) also requires the same type, so a string is never identical to an int.+is an arithmetic operator, so PHP converts"5"to the number5..is the string operator, so PHP converts5to"5".
The operator determines the conversion. This automatic conversion is called type juggling and is explained in PHP Type Juggling; explicit conversion is explained in PHP Casting.
Practical Example: Validating Mixed Input
Data from forms, URLs, JSON, and CSV files must be checked before use, because its type is not guaranteed.
<?php
function describeQuantity(mixed $input): string
{
if (is_int($input)) {
return "Integer quantity: $input";
}
if (is_string($input) && ctype_digit($input)) {
return "Numeric string, converted to: " . (int) $input;
}
return "Invalid quantity (" . get_debug_type($input) . ")";
}
echo describeQuantity(4) . "\n";
echo describeQuantity("12") . "\n";
echo describeQuantity("12abc") . "\n";
echo describeQuantity(2.5) . "\n";
echo describeQuantity(null) . "\n";
Output
Integer quantity: 4
Numeric string, converted to: 12
Invalid quantity (string)
Invalid quantity (float)
Invalid quantity (null)
How It Works
mixeddeclares that the parameter accepts any type, which reflects reality for raw input.is_int()accepts real integers.ctype_digit()checks that a string contains only digits (0–9), so"12"passes and"12abc"fails. It also rejects negative numbers and decimals, which is appropriate for a quantity.(int) $inputconverts the verified string to an integer.get_debug_type()produces a clear type name for the error message.
In production code, filter_var($input, FILTER_VALIDATE_INT) is often used for this purpose; it is covered in PHP Filters.
Common Mistakes
Assuming Form Data Is Numeric
Problem: $_POST['age'] is always a string, even when the user types 25.
Effect: is_int($_POST['age']) is false, and strict type declarations reject it.
Fix: Validate and convert: filter_var($_POST['age'], FILTER_VALIDATE_INT).
Comparing Floats With ==
Effect: 0.1 + 0.2 == 0.3 is false.
Fix: Compare with a tolerance (abs($a - $b) < 0.00001), or use integers or BCMath for exact decimal values.
Using strlen() for Character Counts
Effect: Wrong lengths for non-English text.
Fix: Use mb_strlen().
Relying on gettype() Names in Comparisons
Effect: gettype(1.5) === 'float' is false, because gettype() returns "double".
Fix: Use is_float() for checks, or get_debug_type() for readable names.
Using == When Types Matter
Effect: Values of different types compare as equal unexpectedly.
Fix: Use === by default.
Best Practices
- Use
var_dump()to inspect values;echohides type information. - Use
is_*()functions to check types before processing external data. - Declare parameter, return, and property types in functions and classes.
- Use
===and!==for comparisons unless loose comparison is intended. - Use integers (smallest currency unit) or BCMath for money.
- Use
mb_*functions for text. - Prefer
get_debug_type()in error messages (PHP 8.0+).
Official reference: https://www.php.net/manual/en/language.types.php