Archive for April, 2008

Ternary Conditionals, An alternative to If Then

Posted in Programming on April 12th, 2008 by Jason – Be the first to comment

Ternary Conditionals can be a great way to reduce the amount of code and simplify your life. I think of them as an alternative to if then statements in PHP. Although they do not; and I dont suggest that you try, completely replace the if then statement, they can be used in many cases where you would normally use if then.

Just to give you a brief look at the syntax for one of these conditionals

$value=(condition) ? true_value : false_value;
echo ($i=1) ? '$i is equal to 1' : '$i is not equal to 1';

The first thing you need is your condition, this is put inside the ( ) and followed by the “?”. Ned you will need the action to be performed if true, followed by a colon “:” and the action to be performed if false. Thats it, a pretty simple test. In the above example I want to echo a certain message, based on whether the variable $i is equal to 1. If it is then the echo statement will echo the true value “$i is equal to 1″ and if false, “$i is not equal to 1″.

There are many ways to use these conditionals, but I will leave it up to you to find the best ways to implement it. For now, consider it another tool in the belt.

Post to Twitter Tweet This Post