PASSWORD RESET

Your destination for complete Tech news

PHP

How to use PHP ternary operator?

406 0
< 1 min read

The ternary operator in PHP is a shorthand way of writing an ifelse statement. It has the following syntax:

$result = (condition) ? value_if_true : value_if_false;

Here’s an example of how to use the ternary operator:

$age = 25;
$can_drink = ($age >= 21) ? true : false;

// The same as:
if ($age >= 21) {
    $can_drink = true;
} else {
    $can_drink = false;
}

The ternary operator can also be nested:

$age = 25;
$status = ($age >= 21) ? 'adult' : (($age >= 18) ? 'teen' : 'child');

// The same as:
if ($age >= 21) {
    $status = 'adult';
} else {
    if ($age >= 18) {
        $status = 'teen';
    } else {
        $status = 'child';
    }
}

You should use the ternary operator sparingly, as it can make your code harder to read if overused. It is best suited for simple conditions with a clear and concise value for each branch. For more complex conditions, it is usually better to use a regular ifelse statement.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.