Search code examples
phpoperator-keywordternary

Do these ternary operator output the same result?


Is $time ?: 3600 equivalent to isset($time) ? $time : 3600 ?

Thank you all.


Solution

  • No. There are cases for which they evaluate to the same value, but they are not equivalent.

    <?php
    print $time ?: 3600;
    print "\n";
    print isset($time) ? $time : 3600;
    print "\n\n";
    
    $time = 0;
    print $time ?: 3600;
    print "\n";
    print isset($time) ? $time : 3600;
    print "\n\n";
    
    $time = 30;
    print $time ?: 3600;
    print "\n";
    print isset($time) ? $time : 3600;
    print "\n\n";
    ?>
    

    Output:

    PHP Notice:  Undefined variable: time in /home/hq6/PHP/Test2.php on line 2
    3600
    3600
    
    3600
    0
    
    30
    30