PHP Data Types
PHP Data Types
Section titled “PHP Data Types”PHP Data Types Overview
Section titled “PHP Data Types Overview”Variables in PHP can hold different types of data. PHP is a dynamically typed language, meaning you don’t usually need to declare the type of a variable in advance; PHP determines the type based on the value assigned.
PHP supports the following scalar types:
bool: Represents boolean values (true or false).int: Represents integer (whole) numbers.float: Represents floating-point numbers (also known as doubles or real numbers).string: Represents sequences of characters.
PHP supports the following compound types:
array: Represents an ordered map that can hold multiple values of any type.object: Represents an instance of a user-defined class.callable: Represents a reference to a function or method.iterable: Represents any type that can be looped over withforeach(arrays and objects implementingTraversable).
And two special types:
resource: A special variable holding a reference to an external resource (like a file handle or database connection).null: Represents a variable with no value.
PHP String
Section titled “PHP String”A string is a sequence of characters. Strings can be defined using single quotes ('...'), double quotes ("..."), or heredoc/nowdoc syntax.
- Single quotes (
'...'): Treat content literally, except for\'(literal single quote) and\\(literal backslash). Variables and escape sequences are not interpreted. - Double quotes (
"..."): Interpolate variables (e.g.,"Hello $name") and interpret escape sequences (e.g.,"\n"for newline,"\t"for tab).
<?php$name = "World";$x = "Hello $name!\n"; // Variable interpolated, newline interpreted$y = 'Hello $name!\n'; // Literal string: Hello $name!\n
echo $x;echo $y;?>PHP Integer (int)
Section titled “PHP Integer (int)”An integer is a non-decimal number. The size of an integer depends on the platform (32-bit or 64-bit), although 64-bit is standard on most modern systems.
You can find the maximum and minimum integer values for your system using the constants PHP_INT_MAX and PHP_INT_MIN.
Rules for integers:
- Must contain at least one digit.
- Must not contain a decimal point.
- Can be positive or negative.
- Can be specified in decimal (base 10), hexadecimal (base 16, prefixed with
0x), octal (base 8, prefixed with0), or binary (base 2, prefixed with0b) notation.
The var_dump() function is useful for inspecting a variable’s type and value:
<?php$decimal_int = 1234;$negative_int = -567;$hex_int = 0xFF; // 255 in decimal$octal_int = 0755; // 493 in decimal$binary_int = 0b1010; // 10 in decimal
var_dump($decimal_int);var_dump($hex_int);echo "Max Integer: " . PHP_INT_MAX . "\n";?>Output (example):
int(1234)int(255)Max Integer: 9223372036854775807PHP Float (float)
Section titled “PHP Float (float)”A float (or double) is a number with a decimal point or a number in exponential (scientific) notation.
Warning: Due to the nature of binary floating-point representation, simple decimal fractions like 0.1 or 0.7 cannot be exactly represented. Be cautious when comparing floats for equality; use a small tolerance (epsilon) instead.
<?php$a = 10.365;$b = 2.5e3; // 2.5 * 10^3 = 2500$c = 7E-10; // 7 * 10^-10
var_dump($a);var_dump($b);
// Float comparison issue example$float_sum = 0.1 + 0.7;var_dump($float_sum); // Might output float(0.7999999999999999)var_dump($float_sum == 0.8); // Might output bool(false)!?>PHP Boolean (bool)
Section titled “PHP Boolean (bool)”A boolean represents two possible states: true or false (case-insensitive).
Booleans are primarily used in conditional logic (if, else, loops). Many values can be automatically converted to boolean false: the integer 0, the float 0.0, an empty string "" or '0', an empty array [], and the special value null.
<?php$is_active = true;$has_permission = false;
var_dump($is_active);var_dump((bool) 0); // bool(false)var_dump((bool) "Hello"); // bool(true)?>PHP Array (array)
Section titled “PHP Array (array)”An array is an ordered map, capable of storing multiple values under a single variable name. Arrays can hold values of different types and can be indexed numerically or associatively (using string keys).
Modern PHP uses the short array syntax [] instead of the older array() construct.
<?php// Numerically indexed array (indices start at 0)$colors = ["Red", "Green", "Blue"];var_dump($colors);echo $colors[1]; // Outputs: Green
// Associative array (key-value pairs)$user = [ 'name' => 'John Doe', 'age' => 30, 'city' => 'New York'];var_dump($user);echo $user['age']; // Outputs: 30
// Mixed array$mixed = [10, 'Hello', true, 'city' => 'London'];var_dump($mixed);?>Arrays are fundamental in PHP and covered in more detail in later chapters.
PHP Object (object)
Section titled “PHP Object (object)”An object is an instance of a class. Classes are blueprints defining properties (data) and methods (functions) that operate on that data.
Object-Oriented Programming (OOP) is a major paradigm in modern PHP.
<?php// Define a simple classclass Car { // Property declaration (with type hint PHP 7.4+) public string $make; public string $model;
// Constructor method (called when creating an object) public function __construct(string $make, string $model) { $this->make = $make; $this->model = $model; }
// Method public function getDescription(): string { return "This car is a " . $this->make . " " . $this->model; }}
// Create an object (instance) of the Car class$myCar = new Car("Toyota", "Camry");
// Access properties and call methods using ->var_dump($myCar);echo $myCar->model . "\n"; // Outputs: Camryecho $myCar->getDescription() . "\n"; // Outputs: This car is a Toyota Camry?>OOP concepts like classes, objects, inheritance, and interfaces are covered extensively in dedicated OOP sections.
PHP NULL Value (null)
Section titled “PHP NULL Value (null)”null is a special data type representing the intentional absence of value. A variable is considered null if:
- It has been explicitly assigned the constant
null(case-insensitive). - It has not been assigned a value yet.
- It has been
unset().
<?php$noValue = null;var_dump($noValue); // Outputs: NULL
$x = "Hello world!";var_dump($x);
// Unset the variableunset($x);var_dump($x); // Warning: Undefined variable $x; var_dump will output NULL
var_dump($undefinedVariable); // Warning: Undefined variable; var_dump will output NULL?>PHP Resource
Section titled “PHP Resource”A resource is a special variable type holding a reference to an external resource, such as an open file handle, a database connection, or an image canvas.
Resources are typically created and managed by specific PHP functions (e.g., fopen(), mysqli_connect(), imagecreatefromjpeg()). They often need to be explicitly closed or freed using functions like fclose(), mysqli_close(), imagedestroy() to release system resources.
You generally don’t interact with resources directly beyond passing them to relevant functions. var_dump() will show the type as ‘resource’ and its internal ID.
<?php$filename = 'example.txt';file_put_contents($filename, 'Some data');
// fopen returns a resource on success$fileHandle = fopen($filename, 'r');
if ($fileHandle) { var_dump($fileHandle); // Outputs something like: resource(5) of type (stream) fclose($fileHandle); // Important to close the resource} else { echo "Failed to open file.";}?>