PHP Scalar Data Types Explained

In PHP, data types are used to classify the different kinds of values that variables can hold. Scalar data types are the most fundamental types, representing single values rather than complex collections of data. This article explains the four scalar data types supported by PHP—boolean, integer, float, and string—providing a clear and direct guide on how they work and how to use them in your code.

1. Boolean (bool)

A boolean represents the simplest data type in PHP, expressing a truth value. It can only be one of two values: * true * false

Booleans are typically used in conditional statements and control structures to determine the flow of a program. PHP is case-insensitive regarding boolean keywords, meaning TRUE and False are also valid, though lowercase is standard practice.

$isLoggedIn = true;
$hasAccess = false;

2. Integer (int)

An integer is a non-decimal number between \(-2,147,483,648\) and \(2,147,483,647\) on 32-bit systems (and much larger on 64-bit systems). Integers can be positive, negative, or zero.

PHP supports integers in several formats: * Decimal: Base 10 (e.g., 1234, -56) * Hexadecimal: Base 16, prefixed with 0x (e.g., 0x1A) * Octal: Base 8, prefixed with 0 (e.g., 0123) * Binary: Base 2, prefixed with 0b (e.g., 0b11111111)

$age = 30;
$temperature = -5;

3. Float (float)

Floats, also known as doubles or real numbers, are numbers that contain a decimal point or are expressed in exponential (scientific) notation. Like integers, they can be positive or negative.

$price = 19.99;
$scientificNotation = 1.2e3; // Equivalent to 1200

Note that floating-point numbers have limited precision, so they should not be used for exact calculations, such as currency, without specialized mathematical libraries like BCMath.

4. String (string)

A string is a sequence of characters, where a character is the same as a byte. PHP does not support Unicode natively in its standard string type, though it handles UTF-8 encoded text seamlessly in most contexts.

Strings can be defined in four ways, but the most common are: * Single Quotes ('): Variables and special escape sequences (like \n) are not expanded when enclosed in single quotes. * Double Quotes ("): Variables and escape sequences are parsed and evaluated.

$name = 'Alice';
$greeting = "Hello, $name!"; // Outputs: Hello, Alice!