Bird
Raised Fist0
PHPprogramming~10 mins

Union types in practice in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Union types in practice
Function with Union Type Parameter
↓
Call function with int
→Accept int
↓
Call function with string
→Accept string
↓
Call function with other type
→Error: Type Mismatch
↓
Function returns value
The function accepts either int or string as input. It checks the type and processes accordingly. If input is not int or string, it causes a type error.
Execution Sample
PHP
<?php
function printValue(int|string $value): void {
  echo "Value: $value\n";
}
printValue(10);
printValue("hello");
printValue(3.14); // error
?>
This code defines a function that accepts either an int or a string and prints it. It is called with int, string, and a float (which causes an error).
Execution Table
StepFunction CallParameter TypeAccepted?Output or Error
1printValue(10)intYesValue: 10
2printValue("hello")stringYesValue: hello
3printValue(3.14)floatNoTypeError: Argument 1 passed to printValue() must be of type int|string, float given
💡 Execution stops at step 3 due to TypeError caused by passing float instead of int|string.
Variable Tracker
VariableStartAfter Call 1After Call 2After Call 3
$valueundefined10 (int)"hello" (string)3.14 (float) - error
Key Moments - 2 Insights
Why does passing 3.14 cause an error even though it is a number?
The function only accepts int or string as per the union type int|string. Float is not allowed, so step 3 in the execution_table shows a TypeError.
Can the function accept both int and string without separate overloads?
Yes, union types let the function accept either type in one definition, as shown in steps 1 and 2 where both int and string inputs are accepted.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output when printValue is called with "hello"?
AValue: hello
BValue: 10
CTypeError
DNo output
💡 Hint
Check step 2 in the execution_table where printValue("hello") is called.
At which step does the function call cause a TypeError?
AStep 1
BStep 3
CStep 2
DNo error
💡 Hint
Look at the 'Accepted?' and 'Output or Error' columns in the execution_table.
If the function parameter type was changed to int|float, what would happen at step 3?
AIt would accept only int
BIt would cause a TypeError
CIt would accept 3.14 and print it
DIt would accept string too
💡 Hint
Consider the union type change and how it affects the accepted parameter types.
Concept Snapshot
Union types allow a function parameter or return to accept multiple types.
Syntax: function f(int|string $param): void
The function accepts either int or string.
Passing other types causes a TypeError.
Useful for flexible but type-safe code.
Full Transcript
This example shows a PHP function using union types to accept either an int or a string parameter. The function printValue prints the value passed. When called with 10 (int) or "hello" (string), it works fine and prints the value. When called with 3.14 (float), it causes a TypeError because float is not part of the union type int|string. The execution table traces each call, showing accepted types and outputs or errors. The variable tracker shows how the parameter changes each call. Key moments clarify why float causes an error and how union types allow multiple accepted types in one function. The quiz tests understanding of outputs, error steps, and effects of changing union types. The snapshot summarizes union types as a way to accept multiple types safely in PHP functions.

Practice

(1/5)
1. What does a union type declaration like int|string mean in PHP?
easy
A. The value must be both an integer and a string at the same time.
B. The value can only be a string.
C. The value can only be an integer.
D. The value can be either an integer or a string.

Solution

  1. Step 1: Understand union type syntax

    The | symbol means the value can be one of the listed types.
  2. Step 2: Interpret int|string

    This means the value can be either an integer or a string, not both simultaneously.
  3. Final Answer:

    The value can be either an integer or a string. -> Option D
  4. Quick Check:

    Union type int|string means either int or string [OK]
Hint: Union types allow multiple possible types separated by | [OK]
Common Mistakes:
  • Thinking the value must be both types at once
  • Confusing union with intersection types
  • Assuming only one type is allowed
2. Which of the following is the correct syntax for an optional function parameter that accepts either an array or null using union types?
easy
A. function example(array|null $data = null) {}
B. function example(array&null $data) {}
C. function example(array? $data) {}
D. function example(array|null $data) {}

Solution

  1. Step 1: Identify correct union type syntax

    Union types use | between types, so array|null is correct.
  2. Step 2: Check default value for nullable parameter

    To accept null, the parameter should default to null, so $data = null is needed.
  3. Final Answer:

    function example(array|null $data = null) {} -> Option A
  4. Quick Check:

    Union type with default null = correct syntax [OK]
Hint: Use | for union and default null for optional nullable [OK]
Common Mistakes:
  • Using & instead of | for union
  • Missing default null for nullable parameter
  • Using ? without type for union
3. What will be the output of this PHP code?
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);
medium
A. Number: 10, Text: hello, Unknown type
B. Number: 10, Text: hello, Number: 3.14
C. Unknown type, Text: hello, Unknown type
D. Number: 10, Unknown type, Unknown type

Solution

  1. 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'.
  2. Step 2: Combine outputs

    Outputs joined by commas: 'Number: 10, Text: hello, Unknown type'.
  3. Final Answer:

    Number: 10, Text: hello, Unknown type -> Option A
  4. Quick Check:

    Match on gettype gives expected strings [OK]
Hint: Match gettype results carefully for each input [OK]
Common Mistakes:
  • Assuming float is treated as integer
  • Ignoring default case in match
  • Confusing gettype return values
4. Identify the error in this PHP function using union types:
function process(int|string $input): int {
    if (is_string($input)) {
        return strlen($input);
    } else {
        return $input + 1;
    }
}

process(true);
medium
A. The is_string check is incorrect syntax.
B. The function should return string, not int.
C. Passing a boolean to a parameter expecting int|string causes a TypeError.
D. The function does not handle float inputs.

Solution

  1. Step 1: Check parameter type declaration

    The function expects int|string, so only integers or strings are allowed.
  2. Step 2: Analyze the call with true

    Passing true (boolean) violates the declared union type, causing a TypeError at runtime.
  3. Final Answer:

    Passing a boolean to a parameter expecting int|string causes a TypeError. -> Option C
  4. Quick Check:

    Type mismatch causes error [OK]
Hint: Check argument types match union types exactly [OK]
Common Mistakes:
  • Ignoring type mismatch errors
  • Thinking is_string is invalid syntax
  • Assuming function return type is wrong
5. You want to write a function that accepts either a string or an array of strings and returns a single string. Which of the following implementations correctly uses union types and handles both cases?
hard
A. function joinStrings(string|array $input): string { return implode(', ', $input); }
B. function joinStrings(string|array $input): string { if (is_array($input)) { return implode(', ', $input); } return $input; }
C. function joinStrings(string|array $input): string { if (is_string($input)) { return implode(', ', $input); } return $input; }
D. function joinStrings(array|string $input): string { if (is_array($input)) { return $input; } return implode(', ', $input); }

Solution

  1. Step 1: Check union type declaration

    Both string|array and array|string are valid syntax.
  2. 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 with implode. If input is string, returns it directly. This correctly handles both cases.
  3. 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.
  4. Final Answer:

    function joinStrings(string|array $input): string { if (is_array($input)) { return implode(', ', $input); } return $input; } -> Option B
  5. Quick Check:

    Check type then handle accordingly [OK]
Hint: Check type before processing union inputs [OK]
Common Mistakes:
  • Calling implode on string input
  • Returning array instead of string
  • Not checking input type before processing
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard