0
0
PHPprogramming~10 mins

Nullable types in functions 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 nullable integer parameter in the function.

PHP
<?php
function example([1] $num) {
    return $num;
}
?>
Drag options to blanks, or click blank then click option'
Astring
B?int
Cfloat
Dint
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the question mark and just using 'int' which disallows null.
Using a wrong type like 'string' when integer is needed.
2fill in blank
medium

Complete the function return type to allow returning an integer or null.

PHP
<?php
function getValue(): [1] {
    return null;
}
?>
Drag options to blanks, or click blank then click option'
A?int
Bvoid
Cint
Dstring
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'int' alone disallows returning null.
Using 'void' which means no return value.
3fill in blank
hard

Fix the error in the function parameter type to accept null or string.

PHP
<?php
function greet([1] $name) {
    if ($name === null) {
        return 'Hello, Guest!';
    }
    return "Hello, $name!";
}
?>
Drag options to blanks, or click blank then click option'
A?string
Bstring
Cint
Dbool
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' alone which disallows null.
Using unrelated types like 'int' or 'bool'.
4fill in blank
hard

Fill both blanks to declare a function with a nullable float parameter and nullable float return type.

PHP
<?php
function calculate([1] $value): [2] {
    if ($value === null) {
        return null;
    }
    return $value * 2;
}
?>
Drag options to blanks, or click blank then click option'
A?float
Bfloat
Dint
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'float' without question mark disallows null.
Mixing types like 'int' and 'float'.
5fill in blank
hard

Fill all three blanks to create a function with a nullable string parameter, nullable int parameter, and nullable string return type.

PHP
<?php
function process([1] $text, [2] $count): [3] {
    if ($text === null || $count === null) {
        return null;
    }
    return str_repeat($text, $count);
}
?>
Drag options to blanks, or click blank then click option'
A?string
B?int
Dint
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting question marks, disallowing null.
Using wrong types like 'int' for string parameters.