Short Ternary Operator ( ?: ) - PHP

Description

Short ternary operator ( ?: ) is a conditional operator and a shorthand for an if else block ( making the code more concise ).

The basic syntax : (condition) ?: (value_if_false).

Code :


                    <?php
                        
                    //// Short-ternary operator
                    print("<p>Case 1 : </p>");
                    $a = True; // Declare Variable
                    $a ?: print("False") ;
                    print("<p> a = $a </p>");    
                        
                    print("<p>Case 2 : </p>");
                    $z = False; // Declare Variable  
                    $z ?: print("False") ;
                    print("<p> z = $z </p>");
                        
                    ?>
                        

Output :


                    Case 1 :
                    a = 1
                        
                    Case 2 :        
                    False
                    z =
                        

----The PHP version used in this example is 8.4.5 ----

Previous : $_SERVER - PHP ( request uri - query string ) …

Next : Null Coalescing Operator ( ?? ) - PHP …

^