Bird
Raised Fist0
PHPprogramming~20 mins

Union types in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Union Types Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of function with union type parameter
What is the output of this PHP code using union types?
PHP
<?php
function describe(mixed $value): string {
    if (is_int($value)) {
        return "Integer: $value";
    } elseif (is_string($value)) {
        return "String: $value";
    } else {
        return "Other type";
    }
}

// Call with union type int|string
function show(int|string $input): string {
    return describe($input);
}

echo show(10) . "\n";
echo show("hello") . "\n";
echo show(3.14) . "\n";
A
Integer: 10
String: hello
Fatal error: Uncaught TypeError
B
Fatal error: Uncaught TypeError
String: hello
Other type
C
Integer: 10
String: hello
String: 3.14
D
Integer: 10
String: hello
Other type
Attempts:
2 left
💡 Hint
Remember union types restrict accepted types. The third call uses a float which is not allowed.
❓ Predict Output
intermediate
2:00remaining
Return type union behavior
What will this PHP code output when run?
PHP
<?php
function getValue(bool $flag): int|string {
    if ($flag) {
        return 42;
    } else {
        return "forty-two";
    }
}

var_dump(getValue(true));
var_dump(getValue(false));
A
string(2) "42"
string(9) "forty-two"
B
int(42)
int(0)
CFatal error: Return type must be int|string
D
int(42)
string(9) "forty-two"
Attempts:
2 left
💡 Hint
The function returns either an int or a string depending on the boolean input.
🔧 Debug
advanced
2:00remaining
Identify the error caused by union type mismatch
What error will this PHP code produce when executed?
PHP
<?php
function process(int|string $data): void {
    echo $data;
}

process(100);
process("test");
process(3.14);
AParse error: syntax error, unexpected '3.14' (float literal)
BFatal error: Uncaught TypeError: Argument 1 passed to process() must be int|string, float given
C
Output:
100
test
3.14
DWarning: echo expects parameter 1 to be string, float given
Attempts:
2 left
💡 Hint
Check the type of the third argument passed to the function.
📝 Syntax
advanced
2:00remaining
Which union type declaration is valid?
Which of the following PHP function signatures correctly declares a union type parameter?
Afunction example(int|string $param): void {}
Bfunction example(int | string $param): void {}
Cfunction example(int |string|null $param): void {}
Dfunction example(int|string| $param): void {}
Attempts:
2 left
💡 Hint
Check the spacing and syntax around the union type declaration.
🚀 Application
expert
3:00remaining
Determine the number of valid keys in union typed array
Given this PHP code, how many keys will the resulting array have?
PHP
<?php
/**
 * @param array<int|string, int|string> $input
 * @return array<int|string, int|string>
 */
function transform(array $input): array {
    $result = [];
    foreach ($input as $key => $value) {
        if (is_int($key) && $key % 2 === 0) {
            $result[$key] = (string)$value;
        } elseif (is_string($key) && strlen($key) > 3) {
            $result[$key] = (int)$value;
        }
    }
    return $result;
}

$input = [
    2 => 100,
    3 => 200,
    "name" => "1234",
    "id" => "5678",
    "longkey" => "42"
];

$output = transform($input);
echo count($output);
A2
B4
C3
D5
Attempts:
2 left
💡 Hint
Check which keys meet the conditions inside the loop.

Practice

(1/5)
1. What does a union type in PHP allow you to do?
function example(int|string $value) {}
easy
A. Only accept integer values
B. Accept multiple types for a parameter or return value
C. Only accept string values
D. Combine two functions into one

Solution

  1. Step 1: Understand union type syntax

    The | symbol between types means the parameter can be either type.
  2. Step 2: Analyze the example function

    The function accepts either an int or a string as input.
  3. Final Answer:

    Accept multiple types for a parameter or return value -> Option B
  4. Quick Check:

    Union types allow multiple types [OK]
Hint: Look for the | symbol to spot union types [OK]
Common Mistakes:
  • Thinking union types combine functions
  • Assuming only one type is allowed
  • Confusing union types with type casting
2. Which of the following is the correct syntax for a union type in PHP 8+?
function test(?? $param) {}
easy
A. int|string, float $param
B. int&string $param
C. int|string&float $param
D. int|string $param

Solution

  1. Step 1: Recall union type syntax

    Union types use the | symbol between types, e.g., int|string.
  2. 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.
  3. Final Answer:

    int|string $param -> Option D
  4. Quick Check:

    Union types use | symbol [OK]
Hint: Union types always use | between types [OK]
Common Mistakes:
  • Using & instead of | for union types
  • Separating types with commas
  • Mixing intersection and union syntax incorrectly
3. What will be the output of this PHP code?
function showType(int|string $value) {
    if (is_int($value)) {
        return "Integer: $value";
    } else {
        return "String: $value";
    }
}

echo showType(10) . "\n";
echo showType("hello") . "\n";
medium
A. 10\nhello
B. String: 10\nInteger: hello
C. Integer: 10\nString: hello
D. Error: Type mismatch

Solution

  1. Step 1: Understand the function behavior

    The function checks if the input is an integer or string and returns a formatted string accordingly.
  2. Step 2: Trace the calls

    Calling with 10 (int) returns "Integer: 10". Calling with "hello" (string) returns "String: hello".
  3. Final Answer:

    Integer: 10\nString: hello -> Option C
  4. Quick Check:

    Type check returns correct output [OK]
Hint: Check type with is_int or is_string inside function [OK]
Common Mistakes:
  • Assuming output is just values without labels
  • Confusing string and int outputs
  • Expecting a type error for valid union types
4. Identify the error in this PHP function using union types:
function add(int|float $a, int|float $b): int|float {
    return $a + $b;
}

add(5, "10");
medium
A. Passing a string "10" instead of int or float causes a type error
B. Return type should be only int
C. Union types cannot be used in return types
D. Function should not accept two parameters

Solution

  1. Step 1: Check parameter types

    The function expects parameters of type int or float only.
  2. Step 2: Analyze the function call

    The call passes 5 (int) and "10" (string). String is not allowed, causing a type error.
  3. Final Answer:

    Passing a string "10" instead of int or float causes a type error -> Option A
  4. Quick Check:

    Parameter types must match union types exactly [OK]
Hint: Check argument types match union types exactly [OK]
Common Mistakes:
  • Assuming string '10' is accepted as int
  • Thinking union types disallow return types
  • Ignoring parameter count
5. You want a function that accepts either an array of integers or a single integer and returns the sum. Which union type and code is correct?
function sumValues(?? $input): int {
    if (is_array($input)) {
        return array_sum($input);
    }
    return $input;
}
hard
A. int|array $input
B. int|string $input
C. array|float $input
D. int|bool $input

Solution

  1. Step 1: Identify input types needed

    The function accepts either a single integer or an array of integers.
  2. Step 2: Match union type to input

    int|array $input uses int|array, which matches the requirement. Others include wrong types like string, float, or bool.
  3. Final Answer:

    int|array $input -> Option A
  4. Quick Check:

    Union type matches all accepted input types [OK]
Hint: Match union types exactly to all input types needed [OK]
Common Mistakes:
  • Using string or bool instead of array
  • Not including all input types in union
  • Confusing float with int
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