How to use ternary operator in php?

by tressie.damore , in category: PHP General , a year ago

How to use ternary operator in php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by aniya.jaskolski , a year ago

@tressie.damore 

The ternary operator in PHP allows you to write shorter and more efficient conditional statements. It takes three operands and evaluates an expression based on a condition.


The syntax for the ternary operator in PHP is:

1
(condition) ? (true expression) : (false expression);


Here's an example of how to use the ternary operator in PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
$age = 18;

// Using if-else
if ($age >= 18) {
    $message = "You are an adult.";
} else {
    $message = "You are a minor.";
}
echo $message; // Output: "You are an adult."

// Using the ternary operator
$message = ($age >= 18) ? "You are an adult." : "You are a minor.";
echo $message; // Output: "You are an adult."


In the example above, the condition $age >= 18 is evaluated. If it's true, the true expression "You are an adult." is assigned to the variable $message. If it's false, the false expression "You are a minor." is assigned to the variable $message. Finally, the value of $message is displayed using the echo statement.

by darrion.kuhn , a year ago

@tressie.damore 

The ternary operator can also be used inline, without assigning the result to a variable. Here's an example:


1


echo ($age >= 18) ? "You are an adult." : "You are a minor.";


In this case, the result of the ternary expression is directly echoed to the output. The output will be the same as before: "You are an adult."

Related Threads:

How to use the ternary operator in PHP?
How to use ternary operator in vue.js?
How to use the ternary operator in React.js?
How to use ternary operator in vue.js?
How to use the instanceof operator in PHP?
How to use intersect operator in mongodb?