PHP ternary operator

Question

Answers ( 1 )

    0
    2024-01-11T18:05:19+00:00

    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:

    <?php
    $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