Bird
0
0

Given the array $data = ['name' => null, 'age' => 25];, which code snippet correctly assigns $result to the value of 'name' if it exists and is not null, otherwise to 'Unknown'?

hard📝 Application Q15 of 15
PHP - Operators
Given the array $data = ['name' => null, 'age' => 25];, which code snippet correctly assigns $result to the value of 'name' if it exists and is not null, otherwise to 'Unknown'?
A$result = $data['name'] ?? 'Unknown';
B$result = isset($data['name']) ? $data['name'] : 'Unknown';
C$result = $data['name'] ?: 'Unknown';
D$result = $data['name'] ??= 'Unknown';
Step-by-Step Solution
Solution:
  1. Step 1: Understand the difference between ?? and isset()

    The null coalescing operator returns the right value if the left is null or not set. However, if the key exists with a null value, $data['name'] ?? 'Unknown' returns 'Unknown'.
  2. Step 2: Check each option's behavior

    $result = $data['name'] ?? 'Unknown'; returns 'Unknown' because 'name' is null. $result = isset($data['name']) ? $data['name'] : 'Unknown'; uses isset() which returns false if null, so it returns 'Unknown'. $result = $data['name'] ?: 'Unknown'; uses ?: which treats null as false, so returns 'Unknown'. $result = $data['name'] ??= 'Unknown'; uses ??= which assigns 'Unknown' to $data['name'] if null or unset, then returns it.
  3. Step 3: Choose the best option for the requirement

    The question asks to assign $result to 'name' if it exists and is not null, else 'Unknown'. Since 'name' exists but is null, only $result = isset($data['name']) ? $data['name'] : 'Unknown'; correctly checks existence and returns 'Unknown'. $result = $data['name'] ?? 'Unknown'; and C treat null as missing, $result = $data['name'] ??= 'Unknown'; modifies the array which is not asked.
  4. Final Answer:

    $result = isset($data['name']) ? $data['name'] : 'Unknown'; -> Option B
  5. Quick Check:

    Use isset() to check existence and null separately [OK]
Quick Trick: Use isset() to check key exists and not null [OK]
Common Mistakes:
  • Assuming ?? checks key existence only
  • Using ??= which changes original array
  • Confusing ?: with ?? operator

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes