0
0
PHPprogramming~10 mins

Ternary operator in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Ternary operator
Evaluate condition
Yes
Use value if true
Result
No
Use value if false
Result
The ternary operator checks a condition and returns one value if true, another if false.
Execution Sample
PHP
<?php
$age = 20;
$status = ($age >= 18) ? 'Adult' : 'Minor';
echo $status;
?>
This code checks if age is 18 or more, then sets status to 'Adult' or 'Minor' accordingly.
Execution Table
StepConditionCondition ResultValue if TrueValue if FalseResult assigned to $status
1$age >= 1820 >= 18 is True'Adult''Minor''Adult'
2End of expression---Execution stops
💡 Condition is true, so 'Adult' is assigned to $status and execution ends.
Variable Tracker
VariableStartAfter Step 1Final
$age202020
$statusundefined'Adult''Adult'
Key Moments - 2 Insights
Why does $status get 'Adult' and not 'Minor'?
Because the condition $age >= 18 is true at step 1 in the execution_table, so the true value 'Adult' is chosen.
What if $age was 16? What would happen?
If $age was 16, the condition would be false, so the false value 'Minor' would be assigned to $status instead.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of $status after step 1?
A20
B'Minor'
C'Adult'
Dundefined
💡 Hint
Check the 'Result assigned to $status' column in row 1 of execution_table.
At which step does the ternary operator decide the value of $status?
AStep 2
BStep 1
CBefore Step 1
DAfter Step 2
💡 Hint
Look at the 'Condition Result' and 'Result assigned to $status' columns in execution_table.
If $age was 15, what would be the result assigned to $status?
A'Minor'
B15
C'Adult'
Dundefined
💡 Hint
Think about the condition $age >= 18 and what happens if it is false.
Concept Snapshot
Ternary operator syntax: (condition) ? value_if_true : value_if_false;
It evaluates the condition once.
Returns value_if_true if condition is true.
Returns value_if_false if condition is false.
Useful for simple if-else in one line.
Full Transcript
The ternary operator in PHP is a shortcut for if-else. It checks a condition and returns one value if true, another if false. In the example, we check if $age is 18 or more. Since $age is 20, the condition is true, so $status is set to 'Adult'. If $age was less than 18, $status would be 'Minor'. This operator helps write simple decisions in one line.