Challenge - 5 Problems
Null Coalescing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of null coalescing with nested variables
What is the output of this PHP code snippet?
PHP
<?php $a = null; $b = 0; $c = $a ?? $b ?? 5; echo $c; ?>
Attempts:
2 left
💡 Hint
Remember that null coalescing returns the first value that is not null.
✗ Incorrect
The expression $a ?? $b ?? 5 returns the first non-null value. $a is null, so it checks $b which is 0 (not null), so it returns 0.
❓ Predict Output
intermediate2:00remaining
Null coalescing with undefined variable
What will this PHP code output?
PHP
<?php // Note: error reporting is off for undefined variables error_reporting(0); $x = $undefinedVar ?? 'default'; echo $x; ?>
Attempts:
2 left
💡 Hint
Null coalescing operator handles undefined variables without error.
✗ Incorrect
The null coalescing operator returns the right side if the left side is null or undefined. Since $undefinedVar is not set, it returns 'default'.
❓ Predict Output
advanced2:00remaining
Null coalescing with function return values
What is the output of this PHP code?
PHP
<?php function getValue() { return null; } $result = getValue() ?? 'fallback'; echo $result; ?>
Attempts:
2 left
💡 Hint
Check what the function returns and how null coalescing handles it.
✗ Incorrect
The function returns null, so the null coalescing operator returns the right side 'fallback'.
❓ Predict Output
advanced2:00remaining
Null coalescing with array keys
What will this PHP code output?
PHP
<?php $arr = ['a' => null, 'b' => 2]; $value = $arr['a'] ?? $arr['b'] ?? 5; echo $value; ?>
Attempts:
2 left
💡 Hint
Null coalescing checks if the key exists and is not null.
✗ Incorrect
The key 'a' exists but is null, so it moves to 'b' which is 2 (not null), so it returns 2.
❓ Predict Output
expert3:00remaining
Complex null coalescing with mixed types
What is the output of this PHP code?
PHP
<?php $val1 = false; $val2 = null; $val3 = 0; $result = $val1 ?? $val2 ?? $val3 ?? 'none'; echo gettype($result) . ':' . var_export($result, true); ?>
Attempts:
2 left
💡 Hint
Null coalescing returns the first value that is not null, even if it is false or zero.
✗ Incorrect
The first value $val1 is false but not null, so it returns false. The output shows type boolean and value false.