I'm trying to understand this:
$page = isset($requestvars['page']) ? $requestvars['page'] : 1;
$product = isset($requestvars['product']) ? $requestvars['product'] : ''
But I don't comprehend what "?" does..This would be like a simple if?
Thanks
I'm trying to understand this:
$page = isset($requestvars['page']) ? $requestvars['page'] : 1;
$product = isset($requestvars['product']) ? $requestvars['product'] : ''
But I don't comprehend what "?" does..This would be like a simple if?
Thanks
It's called a ternary operator, and essentially replaces an if else block.
For example:
$page = isset($requestvars['page']) ? $requestvars['page'] : 1;
Could be rewritten as:
if(isset($requestvars['page']))
{
$page = $requestvars['page'];
}
else
{
$page = 1;
}
The ternary operator tells PHP to assign $requestvars['page'] to $page if the value is set, otherwise to assign 1.
This is a ternary operator. It works like an if statement, but it's shorter.
echo ($a === true) ? 'yep' : 'nope';
Since PHP 5.3, there's also a shortest version, the ?: operator, which only tests the expression and return the expression itself in case of success, or the other option otherwise.
$foo = getSomethingFromTheDb();
$default = new stdObject;
$object = $foo ?: $default;
The is a ternary expression.
It is much more clearly displayed as an if/else, but some people really like them.
This is called a Ternary operation. It is basically an inline if.
$product = isset($variable) ? do something if true : do something if false;
They are just short forms for writing an inline if. Very useful for keeping clean code when testing.