0
0
PHPprogramming~10 mins

Union types 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 integer or a string.

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

Complete the code to declare a property that can hold either a float or null.

PHP
<?php
class Sample {
    public [1] $price;
}
?>
Drag options to blanks, or click blank then click option'
Afloat&null
Bfloat|null
Cfloat
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Using '&' instead of '|' for union types.
Forgetting to include null for nullable properties.
3fill in blank
hard

Fix the error in the function parameter type declaration to accept either an array or a string.

PHP
<?php
function process([1] $input) {
    // process input
}
?>
Drag options to blanks, or click blank then click option'
Aarray|string
Barray&string
Carray
Darray|string|null
Attempts:
3 left
💡 Hint
Common Mistakes
Using '&' instead of '|' for union types.
Adding null when not needed.
4fill in blank
hard

Fill both blanks to declare a function that returns either an int or a float and accepts a string or int parameter.

PHP
<?php
function calculate([1] $value): [2] {
    // calculation logic
}
?>
Drag options to blanks, or click blank then click option'
Astring|int
Bint|float
Cfloat|string
Dint
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up parameter and return types.
Using intersection '&' instead of union '|'.
5fill in blank
hard

Fill all three blanks to create a class property with a union type, a constructor parameter with a union type, and a method return type union.

PHP
<?php
class Data {
    private [1] $info;

    public function __construct([2] $info) {
        $this->info = $info;
    }

    public function getInfo(): [3] {
        return $this->info;
    }
}
?>
Drag options to blanks, or click blank then click option'
Astring|int
Dint|string|null
Attempts:
3 left
💡 Hint
Common Mistakes
Using different union types in property and methods.
Including null when not needed.
Using intersection '&' instead of union '|'.