0
0
PHPprogramming~5 mins

Null coalescing in conditions 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 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?
A0
Bnull
CAn error
D'default'
Which operator checks if a variable is set and not null in PHP?
A?? (null coalescing)
B?: (ternary)
C&& (and)
D|| (or)
What happens if you chain null coalescing operators like $a ?? $b ?? $c?
AThrows an error
BReturns the first non-null value among $a, $b, or $c
CReturns null always
DReturns the last value always
Which of these is a correct use of null coalescing in an if condition?
Aif (($val = $data['x'] ?? 10) > 5) { ... }
Bif ($data['x'] ?? 10 > 5) { ... }
Cif ($data['x'] ?: 10 > 5) { ... }
Dif ($data['x'] && 10 > 5) { ... }
Why might null coalescing be preferred over isset() in conditions?
AIt runs faster always
BIt throws errors if variable is missing
CIt is shorter and more readable
DIt only works with objects
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.