Ternary Operator in PHP with Example

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.


(condition_here) ? execute_if_value_true : execute_if_value_false; 

But how does it work? Let’s understand by breaking it into three points.

  • The (condition_here) represents the condition that needs to be evaluated.
  • If the condition_here is true, the code block of execute_if_value_true will be executed.
  • If the condition_here is false, the code block of execute_if_value_false will be executed.

Note: It’s a good idea to use parentheses () 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.

Ternary Operator Example in PHP


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.

Written by
I am a web developer with over 2 years of industry experience, specializing in PHP, JavaScript, MySQLi, and Laravel. I create dynamic and user-friendly web applications, committed to delivering high-quality digital solutions.

Share on:

Related Posts

Improved by: Ayaz Ali Shah

Tags: PHP,