PHP Ternary Operator Explained

The ternary operator in PHP is used to simplify the syntax of conditional statements.

The general format for conditional statements is:

if (条件) {
    $result = 表达式1;
} else {
    $result = 表达式2;
}

The use of the ternary operator can be simplified to:

$result = (条件) ? 表达式1 : 表达式2;

The condition is a boolean expression, if true, it returns the value of expression 1, otherwise it returns the value of expression 2.

For example:

$age = 18;
$canVote = ($age >= 18) ? true : false;

In the code above, if the value of $age is greater than or equal to 18, then the value of $canVote is set to true; otherwise, it is set to false.

bannerAds