Bird
0
0

You have an array of user ages: [15, 22, 17, 30]. Use array_map to create a new array that labels each age as "minor" if under 18, or "adult" otherwise. Which code snippet correctly does this?

hard📝 Application Q8 of 15
PHP - Array Functions
You have an array of user ages: [15, 22, 17, 30]. Use array_map to create a new array that labels each age as "minor" if under 18, or "adult" otherwise. Which code snippet correctly does this?
A$labels = array_map(fn($age) => $age == 18 ? 'minor' : 'adult', [15, 22, 17, 30]);
B$labels = array_map(fn($age) => if ($age < 18) { 'minor' } else { 'adult' }, [15, 22, 17, 30]);
C$labels = array_map(fn($age) => $age > 18 ? 'minor' : 'adult', [15, 22, 17, 30]);
D$labels = array_map(fn($age) => $age < 18 ? 'minor' : 'adult', [15, 22, 17, 30]);
Step-by-Step Solution
Solution:
  1. Step 1: Understand the condition for labeling

    Ages under 18 are "minor", 18 or older are "adult".
  2. Step 2: Check the ternary operator usage

    $labels = array_map(fn($age) => $age < 18 ? 'minor' : 'adult', [15, 22, 17, 30]); correctly uses ternary: $age < 18 ? 'minor' : 'adult'.
  3. Final Answer:

    $labels = array_map(fn($age) => $age < 18 ? 'minor' : 'adult', [15, 22, 17, 30]); -> Option D
  4. Quick Check:

    Correct ternary condition for labeling [OK]
Quick Trick: Use ternary inside array_map callback for conditional labels [OK]
Common Mistakes:
  • Using if statement inside arrow function incorrectly
  • Reversing condition logic
  • Checking equality instead of less than

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes