0
0
PHPprogramming~5 mins

Null coalescing operator in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the null coalescing operator (??) do in PHP?
It returns the value of the left operand if it exists and is not null; otherwise, it returns the right operand.
Click to reveal answer
intermediate
How is the null coalescing operator different from the ternary operator?
The null coalescing operator only checks if a value is set and not null, while the ternary operator evaluates a condition and returns one of two values based on that condition.
Click to reveal answer
beginner
Example: What will this code output?<br>
$name = null;<br>echo $name ?? 'Guest';
It will output 'Guest' because $name is null, so the operator returns the right side value.
Click to reveal answer
intermediate
Can the null coalescing operator be chained? Give an example.
Yes, it can be chained to check multiple variables. Example:<br>
$username = $_GET['user'] ?? $_POST['user'] ?? 'anonymous';
Click to reveal answer
beginner
When was the null coalescing operator introduced in PHP?
It was introduced in PHP 7.0 to simplify checking for null or unset variables.
Click to reveal answer
What will this PHP code output?<br>
$a = null;<br>$b = 'Hello';<br>echo $a ?? $b;
Anull
BHello
CError
DEmpty string
Which PHP version introduced the null coalescing operator (??)?
APHP 5.6
BPHP 7.4
CPHP 7.0
DPHP 8.0
What does the null coalescing operator check for?
AIf a variable is true
BIf a variable is empty string
CIf a variable is false
DIf a variable is set and not null
Which of these is a valid use of the null coalescing operator?
A$value = $x ?? 'default';
B$value = $x ? 'default';
C$value = $x ?: 'default';
D$value = $x || 'default';
Can the null coalescing operator be used to check multiple variables in one expression?
AYes, by chaining multiple ?? operators
BNo, only one variable at a time
COnly with arrays
DOnly inside functions
Explain how the null coalescing operator works in PHP and give a simple example.
Think about checking if a variable exists or has a value, then providing a fallback.
You got /3 concepts.
    Describe a situation where chaining the null coalescing operator is useful.
    Imagine getting user input from different sources with fallback defaults.
    You got /3 concepts.