0
0
PHPprogramming~20 mins

Union types in practice in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Union Types Mastery
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 return
What is the output of this PHP code using union types in the return declaration?
PHP
<?php
function test(int|string $input): int|string {
    if (is_int($input)) {
        return $input * 2;
    }
    return strtoupper($input);
}

echo test(5) . ' ' . test('hello');
ATypeError
B5 hello
C10 hello
D10 HELLO
Attempts:
2 left
💡 Hint
Remember the function returns int or string depending on input type.
Predict Output
intermediate
1:30remaining
Variable type with union type hint
What will be the output of this PHP code that uses union types for a variable?
PHP
<?php
/** @var int|string $var */
$var = 10;
if (is_string($var)) {
    echo 'string';
} elseif (is_int($var)) {
    echo 'int';
} else {
    echo 'other';
}
Aint
Bstring
Cother
DTypeError
Attempts:
2 left
💡 Hint
Check the actual value type assigned to the variable.
🔧 Debug
advanced
2:00remaining
Identify the error with union types in method parameter
What error will this PHP code produce when calling the method with a float argument?
PHP
<?php
class Calculator {
    public function multiply(int|float $a, int|float $b): float {
        return $a * $b;
    }
}

$calc = new Calculator();
echo $calc->multiply(3.5, 2.0);
ATypeError: Argument 1 passed must be int|float, float given
BNo error, outputs 7
CFatal error: Return type must be float, int given
DParse error: Syntax error in union type declaration
Attempts:
2 left
💡 Hint
Check if float is allowed in parameter and return types.
📝 Syntax
advanced
1:30remaining
Which union type declaration is invalid?
Which of the following union type declarations in PHP is invalid and causes a syntax error?
Afunction foo(int|string $param): int|string {}
Bfunction bar(int|float|null $param): int|float|null {}
Cfunction baz(int|void $param): int|void {}
Dfunction qux(string|false $param): string|false {}
Attempts:
2 left
💡 Hint
Check if 'void' can be used in union types.
🚀 Application
expert
2:30remaining
Determine the output of complex union type usage
What is the output of this PHP code that uses union types with nullable and mixed types?
PHP
<?php
function process(int|string|null $value): string|int|null {
    return match(true) {
        is_int($value) => $value * 3,
        is_string($value) => strtoupper($value),
        default => null
    };
}

var_dump(process(4));
var_dump(process('abc'));
var_dump(process(null));
A
int(12)
string(3) "ABC"
NULL
B
int(12)
string(3) "abc"
NULL
CTypeError on null input
D
int(4)
string(3) "ABC"
NULL
Attempts:
2 left
💡 Hint
Check how match expression handles each type and the return values.