Bird
0
0

Given this PHP code:

hard📝 Application Q9 of 15
PHP - File Handling
Given this PHP code:
$json = '{"a":1,"b":2,"a":3}';
$arr = json_decode($json, true);
print_r($arr);

What will be the output and why?
AArray with 'a' => 3 and 'b' => 2 because last duplicate key wins
BArray with 'a' => 1 and 'b' => 2 because first key is kept
CError due to duplicate keys in JSON
DArray with both 'a' keys as separate entries
Step-by-Step Solution
Solution:
  1. Step 1: Understand JSON key uniqueness

    JSON keys must be unique; if duplicates exist, last key overwrites previous.
  2. Step 2: Decode JSON with duplicate keys

    When decoded, the last 'a' key with value 3 overwrites the first 'a' key with value 1.
  3. Final Answer:

    Array with 'a' => 3 and 'b' => 2 because last duplicate key wins -> Option A
  4. Quick Check:

    Duplicate JSON keys last wins [OK]
Quick Trick: Duplicate JSON keys overwrite earlier ones, last wins [OK]
Common Mistakes:
  • Expecting error on duplicate keys
  • Thinking both keys are kept

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes