Last updated on September 30, 2023
The ternary operator is a shortened way to write conditional expressions. It is also known as conditional operator. It helps to reduce the code length, means it allowing you to perform tasks typically handled by an if-statement in just a single line of code.
Syntax:
(condition_here) ? execute_if_value_true : execute_if_value_false;
But how does it work? Let’s understand by breaking it into three points.
(condition_here)
represents the condition that needs to be evaluated.condition_here
is true, the code block of execute_if_value_true
will be executed.condition_here
is false, the code block of execute_if_value_false
will be executed.()
around the condition for clarity, especially when dealing with complex conditions or combining multiple ternary operators in a single line. This practice makes our code more readable.Let’s understand the ternary operators with the examples below.
$isRaining = true;
echo ($isRaining) ? "It's raining here" : "No, there is no raining.";
// output: It's raining here
In this example, we have a variable $isRaining
with a boolean value assigned to it. We want to print a message about the rain updates based on the value of the $isRaining
variable. To achieve this, we use the ternary operator on the variable, which allows us to print rain updates depending on whether the bool value assigned to $isRaining
is true
or false
.
Conclusion:
In summary, the ternary operator is like a shortened way to write conditional expressions. It is also known as conditional operator. It looks at a condition, and depending on whether it’s true or false, it executes the code block accordingly. The example with $isRaining
shows how it can be used to make code simpler when dealing with rain messages in PHP.