Introduction
PHP is a loosely typed (dynamically typed) language, meaning you do not need to explicitly declare a variable’s data type when you create it. PHP automatically determines the type based on the value assigned.
PHP supports 10 primitive, compound, and special data types divided into three main categories:
1. Scalar (Primitive) Types
These hold a single value.
- Boolean (
bool): Represents truth values. It can only betrueorfalse. Commonly used in conditional statements. - Integer (
int): Whole numbers without a decimal point (e.g.,42,-1950). Can be specified in decimal, hexadecimal, octal, or binary notation. - Float (
floatalso calleddoubleorreal): Numbers with fractional parts or scientific notation (e.g.,10.99,3.14159,2.4e3). - String (
string): A sequence of characters enclosed in single (') or double (") quotes (e.g.,"Hello, Developer!").
2. Compound Types
These can hold multiple values or complex structures.
- Array (
array): An ordered map that can hold multiple values of any type. Can be indexed (numeric keys), associative (named keys), or multidimensional. - Object (
object): An instance of a user-defined class containing properties (variables) and methods (functions). - Callable: Functions, methods, or closures that can be passed as arguments or executed dynamically.
- Iterable: Any array or object that can be looped through using a
foreachconstruct.
3. Special Types
- Null (
null): A special type representing a variable with no value. A variable is considered null if it has been assigned the constantNULL, has not been set yet, or has been unset. - Resource (
resource): A special variable holding a reference to an external external resource, such as a database connection, a file handle, or an image stream.
Example: Checking and Casting Data Types
You can check a variable’s type using built-in functions like gettype() or var_dump(), and convert types using type casting:
PHP
<?php
$score = "95.5"; // Currently a string
// Type casting string to float
$floatScore = (float) $score;
// Type casting float to integer
$intScore = (int) $floatScore; // Result: 95
var_dump($intScore); // Output: int(95)
?>
Would you like to explore PHP Arrays (indexed vs. associative arrays) in more detail next?