0
0
PHPprogramming~20 mins

Nullable types in functions in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Nullable Types Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of function with nullable int parameter
What is the output of this PHP code when calling describeAge(null);?
PHP
<?php
function describeAge(?int $age): string {
    if ($age === null) {
        return "Age is unknown.";
    }
    return "Age is $age.";
}
echo describeAge(null);
AAge is unknown.
BAge is 0.
CAge is null.
DTypeError
Attempts:
2 left
💡 Hint
Remember that the question mark before int means the parameter can be null.
Predict Output
intermediate
2:00remaining
Return type with nullable string
What will this PHP code output when calling getName(null);?
PHP
<?php
function getName(?string $name): ?string {
    if ($name === null) {
        return null;
    }
    return strtoupper($name);
}
var_dump(getName(null));
ATypeError
B"NULL"
Cstring(0) ""
DNULL
Attempts:
2 left
💡 Hint
The function returns null explicitly if input is null.
Predict Output
advanced
2:00remaining
Nullable type with default value
What is the output of this PHP code when calling greet();?
PHP
<?php
function greet(?string $name = null): string {
    return $name ? "Hello, $name!" : "Hello, guest!";
}
echo greet();
AHello, guest!
BHello, !
CHello, null!
DTypeError
Attempts:
2 left
💡 Hint
The default value is null and the function checks if $name is truthy.
Predict Output
advanced
2:00remaining
Nullable type with strict type enforcement
What happens when this PHP code runs?
PHP
<?php
declare(strict_types=1);
function multiply(?int $a, int $b): int {
    return ($a ?? 1) * $b;
}
echo multiply(null, 5);
ATypeError
B5
C0
Dnull
Attempts:
2 left
💡 Hint
The null coalescing operator replaces null with 1 before multiplication.
Predict Output
expert
3:00remaining
Nullable type with union and default
What is the output of this PHP code?
PHP
<?php
function format(?string|int $value = null): string {
    return match (true) {
        is_int($value) => "Number: $value",
        is_string($value) => "Text: $value",
        default => "No value",
    };
}
echo format();
ANumber: 0
BTypeError
CNo value
DText:
Attempts:
2 left
💡 Hint
The default parameter is null, which matches the default case in match.