Union types in practice in PHP - Time & Space Complexity
We want to see how using union types affects how long a PHP function takes to run.
Specifically, we ask: does checking multiple types slow down the code as input grows?
Analyze the time complexity of the following code snippet.
function processValue(int|string $value) {
if (is_int($value)) {
return $value * 2;
} elseif (is_string($value)) {
return strlen($value);
}
}
$inputs = [1, "hello", 3, "world"];
foreach ($inputs as $item) {
echo processValue($item) . "\n";
}
This code processes a list of values that can be either numbers or words, handling each type differently.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each item in the input array and checking its type.
- How many times: Once for each item in the array.
As the number of items grows, the function runs once per item, doing a quick type check and simple operation.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 type checks and simple calculations |
| 100 | About 100 type checks and simple calculations |
| 1000 | About 1000 type checks and simple calculations |
Pattern observation: The work grows evenly with the number of inputs, doubling inputs doubles work.
Time Complexity: O(n)
This means the time to run grows directly with the number of items processed.
[X] Wrong: "Using union types makes the function slower in a way that changes how time grows with input size."
[OK] Correct: The type checks happen once per item and are simple, so they add a small fixed cost per item, not changing the overall growth pattern.
Understanding how type checks affect performance helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if the function handled an array of arrays instead of simple types? How would the time complexity change?"
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
