<< Home

Chapter 3: Data Types and Structures

Every PHP variable has a type, which determines what kind of data it can hold and how it behaves in expressions. PHP automatically converts between types when necessary, though you can use explicit casting and type declarations to maintain control. Understanding PHP’s built-in types will help you avoid common mistakes and make your code clearer and more predictable.

💡 PHP uses dynamic typing but supports strong type declarations when you want additional safety. This flexibility allows both quick scripting and large, well-structured applications.

Booleans, Integers, and Floats

These are the simplest scalar types in PHP. Booleans represent truth values, integers represent whole numbers, and floats represent numbers with decimal fractions. Each behaves in familiar mathematical ways, though you should be aware of conversion and precision rules.

Using booleans in logical expressions

Booleans are represented by the constants true and false (case-insensitive). Any value can be converted to a boolean; empty strings, zero, null, and empty arrays evaluate as false.

$active = true;
$emptyString = "";
if ($active) {
  echo "Active user";
}
if (!$emptyString) {
  echo "Empty string is false";
}
⚠️ Avoid testing equality directly with == true or == false. Use implicit conditions such as if ($flag) or if (!$flag) instead.

Working with integers and numeric literals

Integers can be written in decimal, hexadecimal (prefix 0x), octal (prefix 0o), or binary (prefix 0b) form. Integer size depends on the platform (usually 64-bit on modern systems).

$a = 42;
$b = 0xFF;
$c = 0b1010;
echo $a + $b + $c;

Using floats and handling precision

Floats represent real numbers but are subject to rounding errors due to binary representation. Use them for measurements and averages, not for exact currency values. For financial calculations, use integers (representing cents) or arbitrary precision libraries like BCMath.

$price = 9.99;
$quantity = 3;
$total = $price * $quantity;
echo $total;  // 29.97 (may vary slightly internally)

Strings and Encodings

Strings hold text data. PHP supports both single-quoted and double-quoted strings, as well as heredoc and nowdoc syntax for multiline text. Each behaves differently regarding variable interpolation and escape sequences.

Using single and double quotes

Single quotes treat most characters literally. Double quotes interpret escape sequences and replace variables with their values.

$name = "Robin";
echo 'Hello $name';  // literal
echo "Hello $name";  // interpolated

Heredoc and nowdoc for multiline text

Heredoc allows embedding of large text blocks with variable interpolation. Nowdoc behaves like single quotes (no interpolation). Both must start and end with an identifier.

$heredoc = <<<HTML
<p>Welcome, $name</p>
HTML;

$nowdoc = <<<'TEXT'
<p>Literal $name</p>
TEXT;
💡 For large embedded HTML or SQL statements, heredoc improves readability and avoids excessive string concatenation.

Handling encodings safely

PHP strings are sequences of bytes, not necessarily Unicode-aware. To handle multibyte characters properly, enable and use the mbstring extension. For example, mb_strlen() counts characters rather than bytes.

⚠️ A plain strlen() call returns the number of bytes, not characters, so a UTF-8 string with accented letters may count higher than its visible length.

Arrays: Indexed and Associative

Arrays in PHP are versatile structures that act as both ordered lists and key-value maps. The same data type supports numeric and associative keys.

Creating indexed arrays

Use square brackets to create arrays. Numeric keys start from zero unless you specify otherwise.

$colors = ["red", "green", "blue"];
echo $colors[1];  // green

Creating associative arrays

Associative arrays use string keys instead of numbers. This form is useful for representing structured data.

$person = [
  "name" => "Robin",
  "role" => "Author",
  "country" => "UK"
];
echo $person["name"];

Iterating through arrays

Use foreach to iterate over values or keys and values together.

foreach ($person as $key => $value) {
  echo "$key: $value<br>";
}
💡 Arrays preserve insertion order. Use array_values() or array_keys() to extract only what you need.

Objects and Resources

Objects represent instances of classes, while resources represent external entities like file handles or database connections. PHP treats both as special types that you can inspect but not directly manipulate as raw values.

Creating and using objects

Objects are created from classes using the new keyword. Properties are accessed with -> notation.

class Book {
  public string $title;
  function __construct($t) {
    $this->title = $t;
  }
}

$book = new Book("This is PHP");
echo $book->title;

Working with resources

Resources represent connections to external systems such as files or databases. You can identify them using get_resource_type(), but you should not rely on internal details.

$handle = fopen("example.txt", "r");
echo get_resource_type($handle);  // stream
fclose($handle);
⚠️ Always close resources when finished. Open file handles and sockets consume system resources that may run out if left dangling.

Null and Type Juggling

null represents the absence of a value. It is a distinct type with a single value: null. PHP automatically converts values between types when used in different contexts, a behavior known as type juggling.

Using and testing for null

You can assign null to any variable and test it with is_null() or a strict comparison.

$value = null;
if (is_null($value)) {
  echo "No value assigned";
}

Understanding type juggling

When performing operations, PHP often converts values automatically. Strings that contain numbers become integers, and booleans convert to numbers or strings as needed. This can simplify quick scripts but also cause subtle bugs.

echo "5" + 10;         // 15
echo "5 apples" + 10;  // 15 with warning
💡 Use === and !== for strict comparisons to prevent unintended conversions during equality checks.

Working with Mixed and Union Types

PHP 8 introduced the mixed and union types to express multiple possible data forms explicitly. These help document flexible functions that can return or accept more than one type of value.

Declaring union types

Use a vertical bar to combine multiple allowed types. This allows functions to safely accept several related types.

function combine(int|float $a, int|float $b): float {
  return $a + $b;
}

Using the mixed type

The mixed type covers all possible values (scalar, array, object, or null). It is used when you cannot constrain input more precisely.

function describe(mixed $value): void {
  var_dump($value);
}
⚠️ While mixed is useful for broad compatibility, prefer explicit union types wherever possible to retain clarity and type safety.