How to use the ternary operator in PHP?

by haylee.mertz , in category: PHP General , 2 years ago

How to use the ternary operator in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by orpha , 2 years 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.

Member

by denis , a year ago

@haylee.mertz 

In the example, the ternary operator is used as follows:

  1. The condition ($age >= 18) is evaluated, which checks if the $age variable is greater than or equal to 18.
  2. If the condition is true, the value "adult" is assigned to the $status variable.
  3. If the condition is false, the value "minor" is assigned to the $status variable.
  4. Finally, the variable $status is echoed, which outputs "adult" in both cases.


Using the ternary operator can make your code more concise and easier to read, especially when you have simple if-else statements. However, it's important to use it judiciously and not abuse its usage to maintain code readability.