0
0
PHPprogramming~20 mins

Null coalescing in conditions in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Null Coalescing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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;
?>
AError
Bnull
C5
D0
Attempts:
2 left
💡 Hint
Remember that null coalescing returns the first value that is not null.
Predict Output
intermediate
2: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;
?>
ANotice error
Bnull
Cdefault
DEmpty string
Attempts:
2 left
💡 Hint
Null coalescing operator handles undefined variables without error.
Predict Output
advanced
2: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;
?>
Afallback
Bnull
CError: Cannot use null coalescing on function call
DEmpty string
Attempts:
2 left
💡 Hint
Check what the function returns and how null coalescing handles it.
Predict Output
advanced
2: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;
?>
A2
Bnull
C5
DError: Undefined index
Attempts:
2 left
💡 Hint
Null coalescing checks if the key exists and is not null.
Predict Output
expert
3: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);
?>
Ainteger:0
Bboolean:false
CNULL:null
Dstring:'none'
Attempts:
2 left
💡 Hint
Null coalescing returns the first value that is not null, even if it is false or zero.