Home » Blog » Uncategorized » What is the use of ternary operator in php

What is the use of ternary operator in php

The ternary operator in PHP is a shorthand way of performing conditional assignments or expressions. it functions as if statement for instance if the condition  true we assign true or else we assign false depending on condition implemented in ternary operator

Syntax:
(condition) ? (value_if_true) : (value_if_false)

Let look on simple example on ternary operator

$age = 20;
$is_adult = ($age >= 18) ? ‘Yes’ : ‘No’;
echo $is_adult; // Output: Yes
In this example:

The condition $age >= 18 is evaluated.
If condition satisfied it return true or else it return false

More Complex Example
The ternary operator can be nested or used with more complex expressions. However, nesting can reduce readability, so it should be used judiciously.
$score = 75;
$result = ($score >= 90) ? ‘A’ : (($score >= 80) ? ‘B’ : (($score >= 70) ? ‘C’ : ‘F’));
echo $result; // Output: C

in the above code value of  of $result will be ‘A’ or ‘B’ or ‘c’ or ‘F’ depending on the value of $score under the ternary condition

PHP 7+ Null Coalescing Operator
In PHP 7 and later, the null coalescing operator (??) is introduced, which is often used as a shorthand for the ternary operator when checking for null values.

$username = $_GET[‘user’] ?? ‘guest’;
echo $username; // Output: ‘guest’ if ‘user’ is not set in the URL query parameters
This is equivalent to:

$username = isset($_GET[‘user’]) ? $_GET[‘user’] : ‘guest’;
Advantages of the Ternary Operator
Conciseness: It reduces the amount of code needed for simple conditional assignments.
Readability: For simple conditions, it can make the code more readable by eliminating multiple lines of if-else statements.
Disadvantages of the Ternary Operator
Complexity: Overuse or nesting can make the code harder to read and understand.

The ternary operator in PHP is a powerful tool for making your code more concise and readable, especially for simple conditional assignments. However, it should be used carefully to avoid reducing the readability of your code.

 

Leave a Reply