What if your code could accept different types without messy checks and bugs?
Why Union types in PHP? - Purpose & Use Cases
Imagine you are writing a function that can accept either a number or a string. Without union types, you have to write separate functions or add lots of checks everywhere to handle each type manually.
This manual approach is slow and error-prone because you must constantly check the type and write duplicate code. It's easy to forget a case or make mistakes, leading to bugs and confusing code.
Union types let you declare that a function or variable can accept multiple types directly. This makes your code clearer, safer, and easier to maintain because the language itself knows what types are allowed.
function process($value) {
if (is_int($value)) {
// handle int
} elseif (is_string($value)) {
// handle string
} else {
throw new Exception('Invalid type');
}
}function process(int|string $value) {
// handle int or string directly
}Union types enable writing flexible and robust code that clearly communicates what types are accepted, reducing bugs and improving readability.
For example, a function that formats user input might accept either a string or an integer ID. Union types let you declare this clearly so the function works smoothly with both.
Manual type checks are slow and error-prone.
Union types let you accept multiple types cleanly.
This leads to clearer, safer, and easier-to-maintain code.
Practice
function example(int|string $value) {}Solution
Step 1: Understand union type syntax
The|symbol between types means the parameter can be either type.Step 2: Analyze the example function
The function accepts either anintor astringas input.Final Answer:
Accept multiple types for a parameter or return value -> Option BQuick Check:
Union types allow multiple types [OK]
- Thinking union types combine functions
- Assuming only one type is allowed
- Confusing union types with type casting
function test(?? $param) {}Solution
Step 1: Recall union type syntax
Union types use the|symbol between types, e.g.,int|string.Step 2: Check each option
int|string $param uses|correctly. int&string $param uses&which is intersection, not union. int|string&float $param mixes union and intersection incorrectly. int|string, float $param uses a comma which is invalid.Final Answer:
int|string $param -> Option DQuick Check:
Union types use | symbol [OK]
- Using & instead of | for union types
- Separating types with commas
- Mixing intersection and union syntax incorrectly
function showType(int|string $value) {
if (is_int($value)) {
return "Integer: $value";
} else {
return "String: $value";
}
}
echo showType(10) . "\n";
echo showType("hello") . "\n";
Solution
Step 1: Understand the function behavior
The function checks if the input is an integer or string and returns a formatted string accordingly.Step 2: Trace the calls
Calling with 10 (int) returns "Integer: 10". Calling with "hello" (string) returns "String: hello".Final Answer:
Integer: 10\nString: hello -> Option CQuick Check:
Type check returns correct output [OK]
- Assuming output is just values without labels
- Confusing string and int outputs
- Expecting a type error for valid union types
function add(int|float $a, int|float $b): int|float {
return $a + $b;
}
add(5, "10");Solution
Step 1: Check parameter types
The function expects parameters of type int or float only.Step 2: Analyze the function call
The call passes 5 (int) and "10" (string). String is not allowed, causing a type error.Final Answer:
Passing a string "10" instead of int or float causes a type error -> Option AQuick Check:
Parameter types must match union types exactly [OK]
- Assuming string '10' is accepted as int
- Thinking union types disallow return types
- Ignoring parameter count
function sumValues(?? $input): int {
if (is_array($input)) {
return array_sum($input);
}
return $input;
}Solution
Step 1: Identify input types needed
The function accepts either a single integer or an array of integers.Step 2: Match union type to input
int|array $input usesint|array, which matches the requirement. Others include wrong types like string, float, or bool.Final Answer:
int|array $input -> Option AQuick Check:
Union type matches all accepted input types [OK]
- Using string or bool instead of array
- Not including all input types in union
- Confusing float with int
Ready to prove it?
Pass the test and this pattern moves unknown
