The Ternary Operator
Part of the Fundamentals section of Coddy's PHP journey — lesson 30 of 71.
When you have a simple if-else that just assigns a value based on a condition, PHP offers a shorter way to write it: the ternary operator.
The syntax uses ? and : to create a compact one-line conditional:
<?php
$age = 20;
// Using if-else
if ($age >= 18) {
$status = "adult";
} else {
$status = "minor";
}
// Same thing with ternary operator
$status = $age >= 18 ? "adult" : "minor";
echo $status; // adult
?>The structure is: condition ? value_if_true : value_if_false.
PHP evaluates the condition first. If it's true, the expression returns the value after ?. If false, it returns the value after :.
<?php
$score = 45;
$result = $score >= 50 ? "Pass" : "Fail";
echo $result; // Fail
$isLoggedIn = true;
$greeting = $isLoggedIn ? "Welcome back!" : "Please log in";
echo $greeting; // Welcome back!
?>The ternary operator is perfect for simple either-or assignments. For more complex logic with multiple conditions, stick with if-elseif-else statements for better readability.
Challenge
EasyRead two integers from input: a score and a passingScore.
Use the ternary operator to determine the result based on the following:
- If
scoreis greater than or equal topassingScore, the result should bePassed - Otherwise, the result should be
Failed
Print the result on the first line.
Then, read an integer quantity from input. Use the ternary operator to determine the shipping message:
- If
quantityis greater than 10, the message should beFree shipping - Otherwise, the message should be
Standard shipping
Print the shipping message on the second line.
Example:
If the inputs are 75, 60, and 15, the output should be:
Passed
Free shippingIf the inputs are 45, 50, and 5, the output should be:
Failed
Standard shippingCheat sheet
The ternary operator provides a compact way to write simple if-else assignments in a single line.
The syntax is: condition ? value_if_true : value_if_false
<?php
$age = 20;
// Using if-else
if ($age >= 18) {
$status = "adult";
} else {
$status = "minor";
}
// Same thing with ternary operator
$status = $age >= 18 ? "adult" : "minor";
echo $status; // adult
?>PHP evaluates the condition first. If true, it returns the value after ?. If false, it returns the value after :.
<?php
$score = 45;
$result = $score >= 50 ? "Pass" : "Fail";
echo $result; // Fail
$isLoggedIn = true;
$greeting = $isLoggedIn ? "Welcome back!" : "Please log in";
echo $greeting; // Welcome back!
?>Use the ternary operator for simple either-or assignments. For complex logic with multiple conditions, use if-elseif-else statements for better readability.
Try it yourself
<?php
// Read input
$score = intval(fgets(STDIN));
$passingScore = intval(fgets(STDIN));
$quantity = intval(fgets(STDIN));
// TODO: Write your code below
// Use the ternary operator to determine if the score is a pass or fail
// Use the ternary operator to determine the shipping message
// Output the results
echo $result . "\n";
echo $shippingMessage;
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators