Bird
0
0

Given the array $data = ['apple' => 3, 'banana' => 0, 'cherry' => 5, 'date' => 0];, which PHP code correctly extracts only the keys with non-zero values?

hard📝 Application Q15 of 15
PHP - Array Functions
Given the array $data = ['apple' => 3, 'banana' => 0, 'cherry' => 5, 'date' => 0];, which PHP code correctly extracts only the keys with non-zero values?
A$keys = array_keys($data);
B$keys = array_keys(array_filter($data));
C$keys = array_values(array_filter($data));
D$keys = array_filter(array_keys($data));
Step-by-Step Solution
Solution:
  1. Step 1: Filter array to keep non-zero values

    array_filter($data) removes entries with zero values.
  2. Step 2: Extract keys from filtered array

    array_keys() gets keys from the filtered array, giving only keys with non-zero values.
  3. Final Answer:

    $keys = array_keys(array_filter($data)); -> Option B
  4. Quick Check:

    Filter then keys = array_keys(array_filter()) [OK]
Quick Trick: Filter first, then get keys with array_keys(array_filter()) [OK]
Common Mistakes:
  • Using array_values() instead of array_keys() after filtering
  • Not filtering before extracting keys
  • Filtering keys instead of values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes