Bird
0
0

You want to set the variable $category to 'Senior' if $age is 65 or older, 'Adult' if between 18 and 64, and 'Child' otherwise. Which PHP code correctly uses nested ternary operators to achieve this?

hard📝 Application Q8 of 15
PHP - Conditional Statements
You want to set the variable $category to 'Senior' if $age is 65 or older, 'Adult' if between 18 and 64, and 'Child' otherwise. Which PHP code correctly uses nested ternary operators to achieve this?
A$category = ($age >= 65) ? 'Senior' : (($age >= 18) ? 'Adult' : 'Child');
B$category = ($age >= 65) ? 'Senior' : ($age >= 18) ? 'Adult' : 'Child';
C$category = $age >= 65 ? 'Senior' : 'Adult' ? $age >= 18 : 'Child';
D$category = ($age >= 65) ? 'Senior' : ($age < 18) ? 'Child' : 'Adult';
Step-by-Step Solution
Solution:
  1. Step 1: Understand the conditions

    We need to check if age is 65 or more, then 18 or more, else child.
  2. Step 2: Analyze nested ternary usage

    $category = ($age >= 65) ? 'Senior' : (($age >= 18) ? 'Adult' : 'Child'); correctly nests the ternary operators with parentheses to ensure proper evaluation order.
  3. Step 3: Check other options

    $category = ($age >= 65) ? 'Senior' : ($age >= 18) ? 'Adult' : 'Child'; lacks parentheses, which can cause ambiguity. $category = $age >= 65 ? 'Senior' : 'Adult' ? $age >= 18 : 'Child'; has incorrect syntax. $category = ($age >= 65) ? 'Senior' : ($age < 18) ? 'Child' : 'Adult'; reverses conditions incorrectly.
  4. Final Answer:

    $category = ($age >= 65) ? 'Senior' : (($age >= 18) ? 'Adult' : 'Child'); -> Option A
  5. Quick Check:

    Use parentheses to clarify nested ternary [OK]
Quick Trick: Always parenthesize nested ternary conditions [OK]
Common Mistakes:
  • Omitting parentheses in nested ternary expressions
  • Incorrect order of conditions
  • Misplacing colons and question marks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes