Bird
0
0

Given the array $items = ['a' => 1, 'b' => 0, 'c' => 3, 'd' => null];, which foreach loop will print only keys with truthy values?

hard📝 Application Q15 of 15
PHP - Loops
Given the array $items = ['a' => 1, 'b' => 0, 'c' => 3, 'd' => null];, which foreach loop will print only keys with truthy values?
Aforeach ($items as $key => $value) { echo $key; }
Bforeach ($items as $key => $value) { if ($value === 0) echo $key; }
Cforeach ($items as $value) { if ($value) echo $value; }
Dforeach ($items as $key => $value) { if ($value) echo $key; }
Step-by-Step Solution
Solution:
  1. Step 1: Understand truthy values in PHP

    Values like 1 and 3 are truthy; 0 and null are falsy.
  2. Step 2: Analyze each loop's condition

    foreach ($items as $key => $value) { if ($value) echo $key; } prints keys only if value is truthy, matching requirement. Others print keys regardless or check wrong condition.
  3. Final Answer:

    foreach ($items as $key => $value) { if ($value) echo $key; } -> Option D
  4. Quick Check:

    Check value truthiness before echo key [OK]
Quick Trick: Use if ($value) to filter truthy values [OK]
Common Mistakes:
  • Printing keys without condition
  • Checking for zero instead of truthy
  • Not using key => value syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes