Saturday, October 26, 2013

If conditional statement in a single line using Operators (?:)

I often forget how to do the simplified condition using the (?:) symbol.  And it is very hard to search on what you meant to search at times.  It's called the ternary operator logic (?:).

I found a source where it shows just how to do it in different levels of complexity:
http://davidwalsh.name/php-shorthand-if-else-ternary-operators

In case the site goes offline.  The Ternary Logic is the process of using the following syntax: "(condition) ? (true value return) : (false value return)".  This will shorten the if/else statement to a single line.

But often this technique confuses others not familiar with it.  But it is fun way to do it.  I still prefer the long way, but will use it to shorten the code at times.

based on the website source link, here is a sample:
$var = 6;
$var_result = ($var>3 ? true:false); // it will return true

No comments:

Post a Comment