A practical guide to PHP data types with examples, differences between scalar and compound types, type juggling, casting, common pitfalls and best practices for developers in India.
Introduction
Understanding PHP data types is essential for writing reliable web applications. Whether you are beginning PHP development or preparing for interviews, knowing how PHP stores and converts values will help you avoid bugs and write cleaner code. This guide explains the primary PHP data types, provides clear examples, and covers practical tips like type casting, type juggling and common pitfalls, with a focus on use-cases relevant to developers in India.
Quick overview
PHP variables do not require explicit type declarations. PHP uses dynamic typing: a variable's type is determined by the value assigned to it. However, PHP supports a set of core types that shape how values are handled, compared and converted.
Aspect | Details |
---|---|
Scalar types | Include integer, float (double), string and boolean. They hold single simple values. Example: $a = 42; $b = 3.14; $c = "Hello"; $d = true; |
Compound types | Include array and object. Arrays can be indexed or associative. Objects are instances of classes. Example: $arr = [1, 'x' => 2]; $obj = new User(); |
Special type: NULL | Represents a variable with no value. Example: $x = null; Useful to reset or check uninitialized data. |
Resource type | Represents external resources like database connections or file handles. Example: $fh = fopen('file.txt', 'r'); |
Type juggling | Automatic conversion between types during operations, e.g. '2' + 3 becomes numeric addition. Understand behaviour when mixing numbers and strings. |
Type casting | Explicitly convert types using casts or functions: (int) '5' , floatval('3.1') . Useful for validating input and APIs. |
Strict types | PHP supports strict typing for function arguments using declare(strict_types=1); which enforces parameter types and reduces unexpected conversions. |
Common pitfalls | Loose comparisons (== ) can be surprising; prefer strict comparison (=== ). Watch for strings with leading zeros, numeric strings in forms, and float precision issues. |
Scalar types with examples
Scalar types are the simplest building blocks. Here are practical examples you can try in a local PHP file or online sandbox.
Integer
Integers are whole numbers. PHP supports positive and negative integers and different bases.
// decimal
$age = 30;
// hexadecimal
$hex = 0x1A;
// binary
$bin = 0b1010;
Float (double)
Floats are numbers with decimal points. Be careful with precision when dealing with money—use integer cents or BCMath for financial calculations.
$price = 199.99;
$ratio = 1.0 / 3.0; // floating-point precision applies
String
Strings hold text and can be defined with single or double quotes. Double-quoted strings allow variable interpolation.
$name = 'Asha';
$message = "Welcome, $name!"; // interpolation
$path = 'C:\\xampp\\htdocs';
Boolean
Booleans are true or false and are commonly used for conditions.
$isActive = true;
if ($isActive) {
// do something
}
NULL
NULL represents no value. Use it for optional parameters, resetting values, or checking for absence.
$value = null;
if (is_null($value)) {
// handle missing value
}
Compound and special types
Array
Arrays can store lists or key-value pairs. PHP arrays are powerful but remember they are not typed containers.
$list = [1, 2, 3];
$assoc = ['name' => 'Ravi', 'city' => 'Delhi'];
$mix = [0 => 'zero', 'one' => 1, 2 => 'two'];
Object
Objects are instances of classes and let you model real-world entities. Use typed properties and visibility for better design.
class Product {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
$p = new Product('Tea');
Resource
Resources represent handles returned by extensions (files, DB connections). Always close resources when done.
$fp = fopen('data.txt', 'r');
// use the file
fclose($fp);
Type juggling vs type casting
PHP automatically converts types when needed (type juggling). For example, adding string and integer converts the string to number if possible. For predictable behaviour, explicitly cast types.
- Type juggling:
'5' + 2
becomes7
. - Casting:
(int) '5 apples'
yields5
, while(int) 'apples'
yields0
.
Best practices for Indian developers
- Validate and sanitize user input from forms and APIs before casting.
- Prefer strict comparisons (
===
) to avoid unexpected results when values are loosely equal. - Use typed properties and function return types in modern PHP to catch errors early.
- For financial calculations, avoid floats—use integers (paise) or BCMath for arbitrary precision.
- Document expected types in code and use static analysis tools like PHPStan or Psalm for larger projects.
Common pitfalls to watch for
- Loose equality:
0 == 'abc'
is true due to type conversion—use strict checks. - String numeric edge-cases: leading zeros or comma-separated numbers from user input need normalization.
- Floating point precision: compare floats with a tolerance rather than exact equality.
- Resources must be freed: forgetting to close file or DB handles can cause leaks in long-running scripts.
Conclusion
PHP data types form the foundation of predictable and robust applications. Knowing the difference between scalar, compound, and special types, and how PHP converts or casts values, will reduce bugs and improve code clarity. Apply best practices like strict comparisons, explicit casting, and proper validation to build reliable applications for production.
Frequently Asked Questions
1. How do I check a variable's type in PHP?
Use functions like gettype($var)
, is_int($var)
, is_string($var)
, or reflection for objects. Type-checking functions are quick and common in validation logic.
2. When should I use strict types?
Enable strict types in modules where API contracts are important. It helps catch incorrect usage early by enforcing type hints for function arguments and return values.
3. Are PHP arrays the same as arrays in other languages?
PHP arrays are ordered maps that can act as numeric lists or associative maps. They are more flexible but not memory-efficient for large numeric-only lists; consider SPL data structures or generators if needed.
4. How do I handle money values in PHP?
Avoid floating-point for money. Use integers representing the smallest currency unit (e.g., paise) or use libraries like BCMath or arbitrary-precision types for calculations.
5. What is the difference between == and === ?
==
compares values after type juggling; ===
compares both value and type. Prefer ===
when exact comparisons are required to prevent unexpected matches.
6. How can I convert a string to an integer safely?
Use explicit casting (int) $str
or functions like intval($str)
. Validate the input first (for example with filter_var
or regex) if user input is involved.