How to use the ternary operator in PHP?

by haylee.mertz , in category: PHP General , 6 months ago

How to use the ternary operator in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , 6 months ago

@haylee.mertz 

The ternary operator in PHP allows you to write a shorthand if-else statement in a single line of code. It has the following syntax:

1
(condition) ? true_value : false_value;


The condition is evaluated first, and if it's true, the true_value is returned; otherwise, the false_value is returned.


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

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

// Using if-else statement
if ($age >= 18) {
    $status = "adult";
} else {
    $status = "minor";
}
echo $status; // Outputs: "adult"

// Using ternary operator
$status = ($age >= 18) ? "adult" : "minor";
echo $status; // Outputs: "adult"


In the example above, the first block of code uses an if-else statement to set the $status variable based on the $age variable's value. The second block of code achieves the same result using the ternary operator, resulting in more concise code.