How to Use Ternary Operators in PHP

Ternary operators are a handy way to write concise and elegant code in PHP. They are also known as conditional expressions, because they evaluate a condition and return one of two values depending on whether the condition is true or false. In this post, we will learn how to use ternary operators in PHP and see some examples of their benefits.

What are Ternary Operators?

A ternary operator is a shorthand for an if-else statement. It has the following syntax:

(condition) ? (value if true) : (value if false)  

The condition can be any expression that evaluates to a boolean value. The value if true and the value if false can be any valid PHP expressions, such as variables, constants, functions, or other operators.

For example, suppose we want to assign a variable $greeting based on the value of another variable $name. We can use a ternary operator like this:

$name = "Ali";  $greeting = ($name == "Ali") ? "Hello, Ali!" : "Hello, stranger!";  echo $greeting; // outputs "Hello, Ali!"  

This is equivalent to writing an if-else statement like this:

$name = "Ali";  if ($name == "Ali") {    $greeting = "Hello, Ali!";  } else {    $greeting = "Hello, stranger!";  }  echo $greeting; // outputs "Hello, Ali!"  

As you can see, the ternary operator is much shorter and simpler than the if-else statement. It also avoids the need to use curly braces and indentation, which can make the code more readable and maintainable.

How to Use Ternary Operators in PHP

Ternary operators can be used in any context where you need to assign a value based on a condition. For example, you can use them to:

  • Set default values for variables or parameters
  • Validate user input or data
  • Format output or display messages
  • Perform calculations or comparisons

Here are some examples of how to use ternary operators in PHP for these purposes:

Set default values for variables or parameters

Sometimes, you may want to assign a default value to a variable or a parameter if it is not set or empty. For example, suppose you have a function that takes a name as a parameter and returns a greeting. You can use a ternary operator to assign a default name if the parameter is empty:

function greet($name) {    $name = empty($name) ? "Guest" : $name;    return "Hello, $name!";  }    echo greet("Reza"); // outputs "Hello, Reza!"  echo greet(""); // outputs "Hello, Guest!"  

Validate user input or data

Another common use case for ternary operators is to validate user input or data and return an appropriate value or message. For example, suppose you have a form that asks the user to enter their age and you want to check if they are old enough to vote. You can use a ternary operator to return a message based on their age:

$age = $_POST["age"];  $message = ($age >= 18) ? "You can vote!" : "You are too young to vote!";  echo $message;  

Format output or display messages

You can also use ternary operators to format output or display messages based on some conditions. For example, suppose you have a variable that stores the number of likes for a post and you want to display a message based on the number of likes. You can use a ternary operator to display a singular or plural message:

$likes = 5;  $message = ($likes == 1) ? "One person likes this post." : "$likes people like this post.";  echo $message; // outputs "5 people like this post."  

Perform calculations or comparisons

Finally, you can use ternary operators to perform calculations or comparisons based on some conditions. For example, suppose you have two variables that store the prices of two products and you want to calculate the discount based on which product is cheaper. You can use a ternary operator to compare the prices and apply the discount:

$price1 = 100;  $price2 = 150;  $discount = ($price1 < $price2) ? 0.1 : 0.05;  $total = $price1 + $price2 - ($price1 + $price2) * $discount;  echo $total; // outputs 225  

Benefits of Using Ternary Operators in PHP

Using ternary operators in PHP can have several benefits, such as:

  • Reducing the number of lines of code and improving readability
  • Avoiding unnecessary repetition and duplication of code
  • Simplifying logic and making code more expressive
  • Enhancing performance and efficiency of code

However, ternary operators should be used with caution and moderation, as they can also have some drawbacks, such as:

  • Making code more difficult to debug and test
  • Reducing code clarity and readability if overused or nested
  • Introducing errors or bugs if not used correctly or carefully

Therefore, it is advisable to use ternary operators only when they make the code simpler and clearer, and avoid using them when they make the code more complex and confusing.

Conclusion

Ternary operators are a powerful and useful feature of PHP that can help you write concise and elegant code. They can be used to replace simple if-else statements and return one of two values based on a condition. They can be used for various purposes, such as setting default values, validating input, formatting output, or performing calculations. However, they should be used with caution and moderation, as they can also make the code more difficult to debug, test, and understand if overused or nested.