PHP ternary operator


Answers ( 1 )


    The ternary operator in PHP is a shorthand or more compact form of the if-else statement. It is typically used to assign a value to a variable based on a condition. The syntax of the ternary operator in PHP is as follows:

    condition ? value_if_true : value_if_false;

    Here's how it works:

    1. condition is evaluated first. If it's true, then value_if_true is returned. If it's false, then value_if_false is returned.
    2. The result of this operation can then be assigned to a variable or used directly in expressions.

    Here is an example to illustrate its use:

    $age = 20;
    $is_adult = ($age >= 18) ? "Yes" : "No";
    echo $is_adult; // Output: Yes

    In this example, the condition checks if $age is greater than or equal to 18. If the condition is true, $is_adult is set to "Yes". If it is false, $is_adult is set to "No".

    The ternary operator is a convenient and concise way to write simple if-else conditions, especially when assigning values to variables based on a condition. However, for more complex conditions, using a regular if-else statement can be more readable and easier to understand.

Leave an answer