Recall & Review
beginner
What does the null coalescing operator (??) do in PHP?
It returns the left-hand operand if it exists and is not null; otherwise, it returns the right-hand operand.
Click to reveal answer
intermediate
How can you use null coalescing in an if condition to provide a default value?
You can write:
if (($value = $array['key'] ?? 'default') === 'default') { ... } to check if the key exists or use 'default' if not.Click to reveal answer
intermediate
What is the difference between the null coalescing operator (??) and the ternary operator (?:) in PHP?
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 true or false.
Click to reveal answer
intermediate
Can the null coalescing operator be chained in PHP? Give an example.
Yes, you can chain it like:
$value = $a ?? $b ?? $c ?? 'default'; which returns the first non-null value among $a, $b, $c, or 'default'.Click to reveal answer
beginner
Why is null coalescing useful in conditions when working with arrays?
It helps avoid errors when accessing undefined array keys by providing a fallback value, making code safer and cleaner.
Click to reveal answer
What will
$value = $array['key'] ?? 'default'; assign if $array['key'] is not set?✗ Incorrect
The null coalescing operator returns 'default' if $array['key'] is not set or is null.
Which operator checks if a variable is set and not null in PHP?
✗ Incorrect
The null coalescing operator (??) checks if a variable is set and not null.
What happens if you chain null coalescing operators like
$a ?? $b ?? $c?✗ Incorrect
Chaining returns the first operand that is set and not null.
Which of these is a correct use of null coalescing in an if condition?
✗ Incorrect
Assigning with null coalescing inside the condition is valid and clear.
Why might null coalescing be preferred over isset() in conditions?
✗ Incorrect
Null coalescing is concise and improves readability compared to isset() checks.
Explain how the null coalescing operator (??) works in PHP and give an example of its use in a condition.
Think about how to safely get a value or a default.
You got /4 concepts.
Describe the benefits of using null coalescing in conditions when accessing array elements.
Consider what happens if the key does not exist.
You got /3 concepts.