Reputation: 23
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.
Upvotes: 2
Views: 183
Reputation: 1171
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"
Upvotes: 0
Reputation: 146219
$foo = ($variation_id>0) ? $variation_id : $item_id;
means
if($variation_id>0)
{
$foo =$variation_id // if true
}
else
{
$foo =$item_id; // if false
}
Let's brake it
$foo=($variation_id>0) ? // This is condition
$variation_id : // This value will be populated by variable '$foo' if condition is true
$item_id; // This value will be populated by variable '$foo' if condition is false
Known as ternary statement/operation, short cut of if else
Upvotes: 0
Reputation: 79021
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.
Upvotes: 4
Reputation: 2768
This is just a shortcut, goes like this:
lets say you have a function.
In the end you want to return a value, but with an exception if the value is 0.
so you will do:
return ($value != 0) ? this_will_be_returned_if_true : this_will_be_returned_if_false;
you can do that also in variable assigning.
Pattern:
(Bool statement) ? true : false;
Upvotes: 0