Ternary Conditionals in PHP


Ternary Conditionals are one of those things in php that can save some time when writing code and possibly make your code easier to read. I think many people don’t use them because they look a little strange ( at least thats what happened to me ).

if ($iExample == 1)
{
    $bVariable = true;
}
else
{
    $bVariable = false;
}

In the example above, if the statement is true then, it will set $bVariable to true or else it will set it to false. This is a regular conditional statement where if a condition is true something happens or else (if the condition is false) other thing happen. Conditional statements like that could be easily handled with a ternary conditional:

$bVariable = ($iExample == 1) ? true : false;

As you can see the syntax of the Ternary Conditional is pretty simple and looks good as its fits all in one line.

Variable = (condition) ?  its true : its false;

I hope you find this post useful, Cheers!

Entry by | Original code is licensed under the GNU GPLv2 license.

Reactions (5)

  1. Not to mention the syntax is the same (except for using $ for variables) as in C++…

    Useful. Stumbled.

  2. by the way: what’s the name of your wp code plugin? cause I’d like to have it too :-)