PHP Ternary Conditionals quick reference

with variable:

 

$greeting = (date(“G”) < 12) ? ‘Good morning’ : ‘Good afternoon’;
echo $greeting;

 

without:

 

echo (date(“G”) < 12) ? ‘Good morning’ : ‘Good afternoon’;

 

another great example
courtesy of:

http://www.addedbytes.com/php/ternary-conditionals/
alternate color with ternary and modulus:

 

$i = 1;
echo ‘<table>’;
while ($data = mysql_fetch_array($result))
{
echo ‘ <tr>’;
echo ‘ <td bgcolor=”‘;
echo (($i % 2) == 0) ? ‘#eee’ : ‘#ddd’ ;
echo ‘”>’;
echo $data[‘field’];
echo ‘ </td>’;
echo ‘ </tr>’;
$i++;
}
echo ‘</table>’;

 

/* another basic usage */
courtesty of:
http://davidwalsh.name/php-shorthand-if-else-ternary-operators

 

$message = ‘Hello ‘.($user->is_logged_in() ? $user->get(‘first_name’ )  :  ‘Guest’ ) ;

 

also see:
http://php.net/manual/en/language.operators.comparison.php
for more examples,
search the page (F3 in FF) for ternary

 

another nice example from:
http://deadlytechnology.com/web-development-tips/php-ternary-syntax/

 

instead of:

 

$bTest1 = false;
$bTest2 = false;

 

if ($bTest1) {
if ($bTest2) {
echo ‘test 1 true, test 2 true’;
}
else {
echo ‘test 1 true, test 2 false’;
}
}
else {
if ($bTest2) {
echo ‘test 1 false, test 2 true’;
}
else {
echo ‘test 1 false, test 2 false’;
}
}

 

better:

 

echo $bTest1 ? ( $bTest2? ‘test 1 true, test 2 true’ : ‘test 1 true, test 2 false’ ) : ( $bTest2 ? ‘test 1 false, test 2 true ‘ : ‘test 1 false, test 2 false ‘
) ;

Leave a Reply

You must be logged in to post a comment.