0
0
PHPprogramming~10 mins

Union types in practice in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a function that accepts an int or a string.

PHP
<?php
function printValue([1] $value) {
    echo $value;
}
?>
Drag options to blanks, or click blank then click option'
Astring
Bint&string
Cint|string|null
Dint|string
Attempts:
3 left
💡 Hint
Common Mistakes
Using & instead of | for union types.
Adding null when not needed.
Using only one type instead of a union.
2fill in blank
medium

Complete the code to declare a variable that can hold either an array or null.

PHP
<?php
/** @var [1] $data */
$data = null;
?>
Drag options to blanks, or click blank then click option'
Aarray&null
Barray|null
Carray|string
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Using & instead of |.
Using unrelated types like string.
Not including null when needed.
3fill in blank
hard

Fix the error in the function parameter type declaration to accept int or float.

PHP
<?php
function calculateArea([1] $radius) {
    return pi() * $radius * $radius;
}
?>
Drag options to blanks, or click blank then click option'
Aint|float
Bfloat
Cint&float
Dint
Attempts:
3 left
💡 Hint
Common Mistakes
Using & instead of |.
Using only one type.
Using unrelated types.
4fill in blank
hard

Fill both blanks to declare a function that returns int or string and accepts int or string.

PHP
<?php
function convert([1] $input): [2] {
    if (is_int($input)) {
        return (string)$input;
    }
    return strlen($input);
}
?>
Drag options to blanks, or click blank then click option'
Aint|string
Bstring
Cint
Dfloat
Attempts:
3 left
💡 Hint
Common Mistakes
Using different types for parameter and return.
Using only one type instead of union.
Using unrelated types like float.
5fill in blank
hard

Fill all three blanks to create a function that accepts int|string|null and returns string|int|null.

PHP
<?php
function processValue([1] $value): [2] {
    if ($value === null) {
        return null;
    }
    if (is_int($value)) {
        return (string)$value;
    }
    return strlen($value);
}

/** @var [3] $result */
$result = processValue(123);
?>
Drag options to blanks, or click blank then click option'
Aint|string|null
Bstring|int|null
Dstring|null
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up order of types in unions.
Not including null when needed.
Using only one type instead of union.