Ternary Operator in PHP

Ternary Operator in PHP

The PHP Ternary Operator is a shorthand way of writing an if-else statement in a single line. It takes three operands: a condition, a value to return if the condition is true, and a value to return if the condition is false.

The syntax for the ternary operator is:

css

(condition) ? value_if_true : value_if_false;

For example, the following code uses the ternary operator to assign a value to the variable $message based on whether or not the variable $isLoggedIn is true:

$message = ($isLoggedIn) ? “Welcome back!” : “Please log in.”;

This is equivalent to writing:

if ($isLoggedIn) { $message = “Welcome back!”; } else { $message = “Please log in.”; } Using the ternary operator can make code more concise and easier to read, especially when the conditions and values to return are simple. However, it can also make code harder to read if used excessively or with complex conditions.

Apply for PHP Certification!

https://www.vskills.in/certification/certified-php-developer

Back to Tutorials

Worksheet Basics
Introducing the FormView Control

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?