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!

Tags:

Saturday, October 25th, 2008 Web Design

→ If you find this post useful please consider inviting me a cup of tea :) Thanks!

5 Responses to “Ternary Conditionals in PHP”

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

    Useful. Stumbled.

  2. Sumesh on October 26, 2008.
  3. True. Thanks for stopping by Sumesh, im glad you found it useful

  4. Matt on October 26, 2008.
  5. Yes!it’s always uesed.Simple and beautiful syntax.

  6. joe on November 9, 2008.
  7. by the way: what’s the name of your wp code plugin? cause I’d like to have it too :-)

  8. younic on November 17, 2008.
  9. @younic Hello, the plugin is SyntaxHighlighter Plus. Cheers! :)

  10. Matt on November 17, 2008.

About Me

Matt Varone - Matias Varone - sksmatt
HI there,

I'm a freelance creative web developer, UI designer and hobbyist musician.

Twitter Status

Flickr Gallery

    Clutter drawerCS4 Replacement iconsCS4 Replacement iconsMagic

Scrnshots Gallery

  • Screenshot from ScrnShots.com
  • Screenshot from ScrnShots.com
  • new site im working on
  • Screenshot from ScrnShots.com