php ternary operators code example

Example 1: ternary operator in php

=40) ? "pass" : "Fail";
?>

Example 2: php ternary operator

 $var2) ? "right" : "wrong";

#output : right
/*
explination : if condition is true then display the stat1 and if condition is 
worng then display stat2
*/
?>

Example 3: php ternary operators

// Both ternary and if/else returns the same result

// ternary
$result = $condition ? 'foo' : 'bar';

// if/else
if ($condition) {
    $result = 'foo' 
} else {
    $result = 'bar'
}

Example 4: ternary in php

print ($marks>=40) ? "pass" : "Fail";

Example 5: php ternary shorthand

$y = $x ? "true" : "false";

Example 6: php ternary

#Ternary & Shorthand Syntax

';
    }else {
        echo 'You are NOT logged in';
        echo '
'; } //the below is the same thing as above echo ($loggedIn) ? 'You are logged in' : 'You are NOT logged in'; $isRegistered = ($loggedIn == true) ? true : false; echo '
'; echo $isRegistered; //these can be nested too $age = 9; $score = 15; echo'
'; echo 'Your score is: '.($score > 10 ? ($age >10 ? 'Average': ' Exceptional'): ($age > 10 ? 'Horrible':'Average')); echo'
'; ?> //alternative syntax for conditionals and loops

Welcome User

Welcome Guest

//

Welcome User

Welcome Guest

//
//
  • Tags:

    Misc Example