ternary if else php code example
Example 1: php inline if
$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false);
Example 2: write if and else in one line php
$result = ($data->status == 1) ? 'active' : 'disable'
Example 3: php ternary operator
<?php
(if Condition) ? (stat1) : (stat2);
$var1 = 5;
$var2 = 2;
echo $check = ($var1 > $var2) ? "right" : "wrong";
?>
Example 4: if else if ternary php
var name = (variable === 1) ? 'foo' : ((variable === 2) ? 'bar' : 'baz');
Example 5: shorthand if php
$is_admin = ($user['permissions'] == 'admin') ? true : false;
Example 6: php ternary
#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>';
}
echo ($loggedIn) ? 'You are logged in' : 'You are NOT logged in';
$isRegistered = ($loggedIn == true) ? true : false;
echo '<br>';
echo $isRegistered;
$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
<div>
<?php if($loggedIn) { ?>
<h1>Welcome User</h1>
<?php }else{ ?>
<h1>Welcome Guest</h1>
<?php } ?>
</div>
//
<div>
<?php if($loggedIn): ?>
<h1>Welcome User</h1>
<?php else: ?>
<h1>Welcome Guest</h1>
<?php endif; ?>
</div>
//
<div>
<?php foreach($array as $val): ?>
<?php echo $val; ?>
<?php endforeach; ?>
</div>
//
<div>
<?php for($i = 0; $i < 10; $i++): ?>
<li> <?php echo $i; ?></li>
<?php endfor; ?>
</div>