Bird
0
0

Given an array of numbers, which PHP code correctly uses the ternary operator to create a new array labeling each number as 'Even' or 'Odd'?

hard📝 Application Q15 of 15
PHP - Conditional Statements
Given an array of numbers, which PHP code correctly uses the ternary operator to create a new array labeling each number as 'Even' or 'Odd'?
A$numbers = [1,2,3]; $labels = array_map(fn($n) => $n % 2 == 1 ? 'Even' : 'Odd', $numbers);
B$numbers = [1,2,3]; $labels = array_map(fn($n) => $n % 2 == 0 ? 'Odd' : 'Even', $numbers);
C$numbers = [1,2,3]; $labels = array_map(fn($n) => $n % 2 ? 'Even' : 'Odd', $numbers);
D$numbers = [1,2,3]; $labels = array_map(fn($n) => $n % 2 == 0 ? 'Even' : 'Odd', $numbers);
Step-by-Step Solution
Solution:
  1. Step 1: Understand the condition for even or odd

    A number is even if $n % 2 == 0, otherwise odd.
  2. Step 2: Check each option's condition and labels

    $numbers = [1,2,3]; $labels = array_map(fn($n) => $n % 2 == 0 ? 'Even' : 'Odd', $numbers); correctly labels even numbers as 'Even' and odd as 'Odd'. Others swap or invert labels.
  3. Final Answer:

    $numbers = [1,2,3]; $labels = array_map(fn($n) => $n % 2 == 0 ? 'Even' : 'Odd', $numbers); -> Option D
  4. Quick Check:

    Even check with ternary = correct labeling [OK]
Quick Trick: Even numbers have remainder 0 when divided by 2 [OK]
Common Mistakes:
  • Swapping 'Even' and 'Odd' labels
  • Using wrong modulo condition
  • Confusing truthy/falsy values in ternary

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes