Recall & Review
beginner
What is the ternary operator in PHP?
The ternary operator is a short way to write an if-else statement. It uses the syntax: condition ? value_if_true : value_if_false.
Click to reveal answer
beginner
How does the ternary operator work in PHP?
It checks the condition before the question mark (?). If true, it returns the value after the question mark and before the colon (:). If false, it returns the value after the colon (:).
Click to reveal answer
beginner
Rewrite this if-else using ternary operator:<br>
if ($age >= 18) { $status = 'adult'; } else { $status = 'minor'; }$status = ($age >= 18) ? 'adult' : 'minor';
Click to reveal answer
intermediate
Can the ternary operator be nested in PHP?
Yes, you can nest ternary operators inside each other, but it can make code harder to read. Use parentheses to clarify.
Click to reveal answer
beginner
What is the benefit of using the ternary operator?
It makes code shorter and easier to write for simple conditions, reducing the need for multiple lines of if-else statements.
Click to reveal answer
What does this PHP code output?<br>
echo (5 > 3) ? 'Yes' : 'No';
✗ Incorrect
Since 5 is greater than 3, the condition is true, so it outputs 'Yes'.
Which symbol separates the true and false parts in a ternary operator?
✗ Incorrect
The colon (:) separates the value if true from the value if false.
What is the correct syntax for a ternary operator in PHP?
✗ Incorrect
The ternary operator syntax is condition ? value_if_true : value_if_false.
Can ternary operators replace all if-else statements?
✗ Incorrect
Ternary operators are best for simple conditions; complex logic is clearer with if-else.
What will this code output?<br>
$x = 10; echo ($x < 5) ? 'Small' : 'Large';
✗ Incorrect
Since 10 is not less than 5, the condition is false, so it outputs 'Large'.
Explain how the ternary operator works in PHP and give a simple example.
Think of it as a short if-else in one line.
You got /6 concepts.
Describe when it is better to use a ternary operator instead of an if-else statement.
Use it for quick decisions, not for complicated checks.
You got /4 concepts.