Union types let you say a value can be one of several types. This helps your code accept different kinds of inputs safely.
Union types in practice in PHP
function example(int|string $value): void { // code here }
Use the pipe character | to separate types.
Union types were introduced in PHP 8.0.
function printValue(int|string $value): void { echo $value; }
function calculate(int|float $number): float { return $number * 2; }
function greet(string|null $name): void { if ($name === null) { echo "Hello, guest!"; } else { echo "Hello, $name!"; } }
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 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);
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.
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.
Practice
int|string mean in PHP?Solution
Step 1: Understand union type syntax
The|symbol means the value can be one of the listed types.Step 2: Interpret
This means the value can be either an integer or a string, not both simultaneously.int|stringFinal Answer:
The value can be either an integer or a string. -> Option DQuick Check:
Union typeint|stringmeans either int or string [OK]
- Thinking the value must be both types at once
- Confusing union with intersection types
- Assuming only one type is allowed
Solution
Step 1: Identify correct union type syntax
Union types use|between types, soarray|nullis correct.Step 2: Check default value for nullable parameter
To accept null, the parameter should default to null, so$data = nullis needed.Final Answer:
function example(array|null $data = null) {} -> Option AQuick Check:
Union type with default null = correct syntax [OK]
- Using & instead of | for union
- Missing default null for nullable parameter
- Using ? without type for union
function describe(mixed $value): string {
return match (gettype($value)) {
'integer' => 'Number: ' . $value,
'string' => 'Text: ' . $value,
default => 'Unknown type'
};
}
echo describe(10) . ', ' . describe('hello') . ', ' . describe(3.14);Solution
Step 1: Analyze the match expression with gettype()
For 10, gettype returns 'integer', so output is 'Number: 10'. For 'hello', gettype returns 'string', so output is 'Text: hello'. For 3.14, gettype returns 'double', which matches default case 'Unknown type'.Step 2: Combine outputs
Outputs joined by commas: 'Number: 10, Text: hello, Unknown type'.Final Answer:
Number: 10, Text: hello, Unknown type -> Option AQuick Check:
Match on gettype gives expected strings [OK]
- Assuming float is treated as integer
- Ignoring default case in match
- Confusing gettype return values
function process(int|string $input): int {
if (is_string($input)) {
return strlen($input);
} else {
return $input + 1;
}
}
process(true);Solution
Step 1: Check parameter type declaration
The function expectsint|string, so only integers or strings are allowed.Step 2: Analyze the call with
Passingtruetrue(boolean) violates the declared union type, causing a TypeError at runtime.Final Answer:
Passing a boolean to a parameter expecting int|string causes a TypeError. -> Option CQuick Check:
Type mismatch causes error [OK]
- Ignoring type mismatch errors
- Thinking is_string is invalid syntax
- Assuming function return type is wrong
Solution
Step 1: Check union type declaration
Bothstring|arrayandarray|stringare valid syntax.Step 2: Verify handling of each type
function joinStrings(string|array $input): string { if (is_array($input)) { return implode(', ', $input); } return $input; } checks if input is array, then joins withimplode. If input is string, returns it directly. This correctly handles both cases.Step 3: Identify errors in other options
function joinStrings(string|array $input): string { return implode(', ', $input); } tries to implode without checking type, causing error if input is string. function joinStrings(string|array $input): string { if (is_string($input)) { return implode(', ', $input); } return $input; } incorrectly calls implode on string input. function joinStrings(array|string $input): string { if (is_array($input)) { return $input; } return implode(', ', $input); } returns array directly without joining.Final Answer:
function joinStrings(string|array $input): string { if (is_array($input)) { return implode(', ', $input); } return $input; } -> Option BQuick Check:
Check type then handle accordingly [OK]
- Calling implode on string input
- Returning array instead of string
- Not checking input type before processing
Ready to prove it?
Pass the test and this pattern moves unknown
