Challenge - 5 Problems
Union Types Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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');
Attempts:
2 left
💡 Hint
Remember the function returns int or string depending on input type.
✗ Incorrect
The function doubles the integer input and converts string input to uppercase. So test(5) returns 10 and test('hello') returns 'HELLO'.
❓ Predict Output
intermediate1: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'; }
Attempts:
2 left
💡 Hint
Check the actual value type assigned to the variable.
✗ Incorrect
The variable $var is assigned the integer 10, so is_int($var) is true and 'int' is printed.
🔧 Debug
advanced2: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);
Attempts:
2 left
💡 Hint
Check if float is allowed in parameter and return types.
✗ Incorrect
The method accepts int or float for parameters and returns a float. Multiplying 3.5 and 2.0 returns 7.0 with no error.
📝 Syntax
advanced1:30remaining
Which union type declaration is invalid?
Which of the following union type declarations in PHP is invalid and causes a syntax error?
Attempts:
2 left
💡 Hint
Check if 'void' can be used in union types.
✗ Incorrect
'void' cannot be used as a union type with other types. It is only valid alone as a return type.
🚀 Application
expert2: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));
Attempts:
2 left
💡 Hint
Check how match expression handles each type and the return values.
✗ Incorrect
For int input 4, it returns 4*3=12. For string 'abc', it returns 'ABC'. For null, it returns null. var_dump shows types and values.