April 10, 2012

What is this PHP Syntax: ($variation_id>0) ? $variation_id : $item_id;

Question by user1325258

Is someone able to explain the meaing of the following statment, and the type of php it is reffering to so I can do further research:

$foo = ($variation_id>0) ? $variation_id : $item_id;

I have tried search but don’t really know what i’m searching for.

What I am trying to find out is the name and meaning of the following syntax
? / : and is ($variation_id>0) just a shorthand if statement ?

— I just stumbled upon conditional variables although a nice simple explanation would still be appreciated.

Answer by LAW

That is a ternary condition. If the condition on the left before the ‘?’ is true, it executes the statement after the ‘?’ and before the colon. if not, then it executes the statement after.

In english, this says “use the variation id if it is greater than zero, else use item id”

Answer by Starx

That structure is called ternary structure and in a short form of If … Else

Your Snippet:

$foo = ($variation_id>0) ? $variation_id : $item_id;

Converts to

if($variation_id>0) {
   $foo = $variation_id;
} else {
   $foo = $item_id;
}

Basically, the syntax will come down to something like this

$variable = (<CONDITION>) ? <TRUE EXPRESSION> : <FALSE EXPRESSION>;

You can also combine multiple ternary structure in one line, but it better if you use normal if, if this is over complicated.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!