PHP Data Types

Ma Mahalakshmi V Updated 14 Nov 2026
11 min read ·Lesson 17 of 256

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.

CategoryTypeExampleHolds
Scalar (single value)booltrue, falseA truth value
int42, -7, 0x1FWhole numbers
float3.14, 1.5e3Decimal numbers
string"Hello", 'PHP'Text (a sequence of bytes)
Compound (contain other values)array[1, 2, 3], ['name' => 'Asha']Ordered key–value collections
objectnew DateTime()Instances of classes, with properties and methods
callable'strtoupper', fn($x) => $x * 2Anything that can be called like a function
iterableArrays, generatorsAnything usable in foreach
SpecialnullnullNo value
resourcefopen('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

FunctionReturnsNotes
var_dump($v)Prints type and valueBest 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 namePHP 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 / falseBest 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") is false because the value is a string that contains digits.
  • is_numeric("42") is true because 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 (0 or 0o), 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_MIN to PHP_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 the mb_* 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.
  • instanceof checks 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://memory is 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 a CurlHandle object and imagecreate() returns a GdImage object instead of resources. File streams from fopen() 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" equals 5.
  • === (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 number 5.
  • . is the string operator, so PHP converts 5 to "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

  • mixed declares 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) $input converts 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; echo hides 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

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Tutorial Index PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about PHP Data Types and get answers drawn from it.

Signed-in readers only.