php ternary operators
snippet in php

php ternary operator

user2389

<?php 
#Syntex  
(if Condition) ? (stat1) : (stat2);

#example
$var1 = 5;
$var2 = 2;

echo $check = ($var1 > $var2) ? "right" : "wrong";

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

ternary operator in php

user3739

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

ternary in php

user7760

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

php ternary operators

user1495

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

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

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

php ternary shorthand

user6161

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

php ternary

user1420

#Ternary & Shorthand Syntax

<?php
    $loggedIn = false;
    $array =[1,2,3,4,5,6];
    if($loggedIn){
        echo 'You are logged in';
        echo '<br>';
    }else {
        echo 'You are NOT logged in';
        echo '<br>';
    }
    //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 '<br>';
    echo $isRegistered;

    //these can be nested too
    $age = 9;
    $score = 15;
    echo'<br>';
    echo 'Your score is: '.($score > 10 ? ($age >10 ? 'Average': '
    Exceptional'): ($age > 10 ? 'Horrible':'Average'));
    echo'<br>';

?>

  //alternative syntax for conditionals and loops
<!-- alternative syntax for conditionals and loops -->
<div>
<?php if($loggedIn) { ?>
    <h1>Welcome User</h1>
<?php }else{ ?>
    <h1>Welcome Guest</h1>
<?php } ?>
</div>
//<!-- a better way that looks better -->
<div>
<?php if($loggedIn):  ?>
    <h1>Welcome User</h1>
<?php else: ?>
    <h1>Welcome Guest</h1>
<?php endif; ?>
    
</div>

//<!-- An Array can be used too -->
<div>
<?php foreach($array as $val):  ?>
    <?php echo $val; ?>
<?php endforeach; ?>
    
</div>
//<!-- Can also use loops this way -->

<div>
<?php for($i = 0; $i < 10; $i++):  ?>
    <li> <?php echo $i; ?></li>
<?php endfor; ?>
    
</div>