Union types let you say a value can be one of several types. This helps your code accept different kinds of inputs safely.
0
0
Union types in practice in PHP
Introduction
When a function can accept either a number or a string as input.
When a variable might hold an integer or a float depending on the situation.
When you want to allow null or a specific type for a parameter.
When working with data that can come in multiple formats, like a string or an array.
When you want to make your code clearer about what types are allowed.
Syntax
PHP
function example(int|string $value): void { // code here }
Use the pipe character | to separate types.
Union types were introduced in PHP 8.0.
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 an integer or a float and returns a float result.
PHP
function calculate(int|float $number): float { return $number * 2; }
This function accepts a string or null and greets accordingly.
PHP
function greet(string|null $name): void { if ($name === null) { echo "Hello, guest!"; } else { echo "Hello, $name!"; } }
Sample Program
This program shows how a function can accept an integer, string, or null using union types. It prints a message based on the input type.
PHP
<?php function describeInput(int|string|null $input): void { if (is_int($input)) { echo "You gave an integer: $input\n"; } elseif (is_string($input)) { echo "You gave a string: $input\n"; } else { echo "You gave nothing (null)\n"; } } describeInput(42); describeInput("hello"); describeInput(null);
OutputSuccess
Important Notes
Union types improve code safety by restricting inputs to expected types.
Use is_int(), is_string(), or is_null() to check the actual type inside the function.
Union types cannot be combined with nullable shorthand ?Type if you already use |null.
Summary
Union types let a value be one of several types using the | symbol.
They help functions accept flexible inputs while keeping code safe.
Check the actual type inside the function to handle each case properly.