Bird
0
0

Which of the following PHP statements correctly uses the ternary operator to assign $result based on $num being greater than 0?

easy📝 Syntax Q3 of 15
PHP - Conditional Statements
Which of the following PHP statements correctly uses the ternary operator to assign $result based on $num being greater than 0?
A$result = $num > 0 ? 'Positive'; 'Non-positive';
B$result = ($num > 0) ? 'Positive' 'Non-positive';
C$result = ($num > 0) ? 'Positive' : 'Non-positive';
D$result = ($num > 0) ? 'Positive' && 'Non-positive';
Step-by-Step Solution
Solution:
  1. Step 1: Identify the ternary operator syntax

    The ternary operator syntax is: condition ? value_if_true : value_if_false.
  2. Step 2: Check each option

    $result = ($num > 0) ? 'Positive' : 'Non-positive'; correctly uses the syntax with parentheses and colon separating true and false values. Options B, C, and D have syntax errors or misuse operators.
  3. Final Answer:

    $result = ($num > 0) ? 'Positive' : 'Non-positive'; -> Option C
  4. Quick Check:

    Colon separates true and false parts [OK]
Quick Trick: Ternary needs '?' and ':' to separate parts [OK]
Common Mistakes:
  • Omitting the colon ':' between true and false values
  • Using logical operators instead of ':'
  • Missing parentheses around the condition

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes