PHP

The ? operator

There is one expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:

Syntax:

<?php
    $first ? $second : $third
?>

If the value of the first subexpression is TRUE (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression.
Otherwise, the third subexpression is evaluated, and that is the value.

Example:

<?php
    echo "5 is greater than 8?<br />";
    echo "Ans: ";
    echo (5 > 8) ? "Yes" : "No";
?>

Output:

Tutorialik.com
5 is greater than 8?
Ans: No

Example:

Another example to find maximum number

<?php
    $a = 5;
    $b = 8;
    $max = $a > $b ? $a : $b;
    echo $max." is Max";
?>

Output:

Tutorialik.com
8 is Max

Example:

Above example is identical to this if/else statement.

<?php
    $a = 5;
    $b = 8;

    if ($a > $b) {
        $max = $a;
    } else {
        $max = $b;
    }
    echo $max." is Max";
?>

Output:

Tutorialik.com
8 is Max



Subscribe us on Youtube

Share This Page on


Ask Question