0
0
PHPprogramming~5 mins

Union types in PHP

Choose your learning style9 modes available
Introduction

Union types let you say a value can be one of several types. This helps your code accept different kinds of data safely.

When a function can accept more than one type of input, like a number or a string.
When a variable might hold different types at different times.
When you want to be clear about all possible types a value can have.
When you want to avoid errors by checking types before using values.
Syntax
PHP
function example(int|string $value): void {
    // code here
}

Use the pipe symbol | to separate types.

Union types are supported in PHP 8.0 and later.

Examples
This function accepts either an integer or a string and prints it.
PHP
function printValue(int|string $value): void {
    echo $value;
}
This function accepts a string or an array and returns its length.
PHP
function getLength(string|array $input): int {
    return is_string($input) ? strlen($input) : count($input);
}
Using mixed is a broader type, but union types are more specific.
PHP
function process(mixed $data): void {
    if (is_int($data) || is_string($data)) {
        echo "Data is int or string: $data";
    }
}
Sample Program

This program defines a function that accepts either an integer or a string. It checks the type and prints a message accordingly.

PHP
<?php

function describeValue(int|string $value): void {
    if (is_int($value)) {
        echo "Integer: $value\n";
    } else {
        echo "String: $value\n";
    }
}

describeValue(10);
describeValue("hello");
OutputSuccess
Important Notes

Union types improve code clarity and reduce bugs by enforcing allowed types.

Nullable types like ?int can be written as int|null with union types.

Union types cannot contain duplicate types or void.

Summary

Union types let a value be one of several types using the | symbol.

They help functions and variables accept multiple types safely.

Supported from PHP 8.0 onwards.