Bird
0
0

Given an array $items = ['pen' => 3, 'book' => 5, 'eraser' => 2], write a foreach loop to create a new array $doubled where each value is doubled. Which code snippet correctly does this?

hard📝 Application Q8 of 15
PHP - Loops
Given an array $items = ['pen' => 3, 'book' => 5, 'eraser' => 2], write a foreach loop to create a new array $doubled where each value is doubled. Which code snippet correctly does this?
A$doubled = []; foreach ($items as $key => $value) { $doubled[$key] = $value * 2; }
B$doubled = []; foreach ($items as $value) { $doubled[] = $value * 2; }
Cforeach ($items as $key => $value) { $doubled[] = $key * 2; }
D$doubled = []; foreach ($items as $key, $value) { $doubled[$key] = $value * 2; }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    Create a new array with the same keys but values doubled.
  2. Step 2: Check foreach syntax and assignment

    $doubled = []; foreach ($items as $key => $value) { $doubled[$key] = $value * 2; } correctly uses key-value syntax and assigns doubled values preserving keys.
  3. Final Answer:

    $doubled = []; foreach ($items as $key => $value) { $doubled[$key] = $value * 2; } -> Option A
  4. Quick Check:

    Use key => value and assign doubled value to new array [OK]
Quick Trick: Use $newArray[$key] = $value * 2 inside foreach [OK]
Common Mistakes:
  • Ignoring keys when assigning
  • Using wrong foreach syntax
  • Multiplying keys instead of values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes