The Blueprint
PHP’s Ternary operator is fast becoming one of my favorite functions to use due to it’s ease to write and how it can clean up the code making it much easier to understand. If you don’t know what a ternary operator is, in short, it is a shortened version of an If/Else statement. Let’s take a look at the code as it is fairly self explanatory as to how it works.
First up is the well known If/Else:
if($weather == 'rain') {
$plans = 'Stay Inside';
} else {
$plans = 'Go Outside';
}
And now the Ternary.
Note: If the statement in () is true then it return the first value, otherwise it returns the second value:
$plans = ($weather == 'rain') ? 'Stay Inside' : 'Go Outside';
There are tons of examples out there about the use of the ternary and I recommend doing some Google searches for more examples and explanations. No need for me to restate what everyone else already has, including the PHP.net site. The one thing that I fail to see mentioned about this code is the one thing that really cleared up how to use it. The ternary operator functionality is to always returns a value. In the prior example the code will return a value that is stored in the variable $plans.
But we have to realize that the ternary code can stand on it’s own and doesn’t need to have a variable like $plans to store it’s returned value. Here’s an example of it used in a function.
function plans($weather) {
return ($weather == ‘rain’) ? ‘Stay Inside’ : ‘Go Outside’;
}
[/sourcecode']
Because the ternary code is so short and simple it allows us to use it inline other code without making it bulky on “overcoded”. To me, that is the real power of this operator. Once you and your team become familiar with this operator you will find your code get smaller and actually easier to read and faster to write.
Search The Blog
Code & Projects
Categories
Archives
- April 2010
- October 2009
- September 2009
- August 2009
- June 2009
- May 2009
- April 2009
- February 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- April 2008
- March 2008
- February 2008
- July 2007