0
0
PHPprogramming~5 mins

Ternary operator in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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';
ANo
BYes
C5 > 3
DError
Which symbol separates the true and false parts in a ternary operator?
A:
B?
C;
D,
What is the correct syntax for a ternary operator in PHP?
Aif (condition) true_value else false_value;
Bcondition : true_value ? false_value;
Ccondition ? false_value : true_value;
Dcondition ? true_value : false_value;
Can ternary operators replace all if-else statements?
ANo, only simple conditions
BOnly with numbers
COnly in loops
DYes, always
What will this code output?<br>
$x = 10; echo ($x < 5) ? 'Small' : 'Large';
A10
BSmall
CLarge
DError
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.