1

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

suspectus
  • 16,548
  • 8
  • 49
  • 57
user2238244
  • 229
  • 1
  • 4
  • 13

4 Answers4

8

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.

BenM
  • 52,573
  • 26
  • 113
  • 168
  • Wow you type extremely fast. I was only half way through... and now I've just realised you made an edit on his post too. Sad :( +1 still. – Albzi Feb 05 '14 at 16:16
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;
lsouza
  • 2,448
  • 4
  • 26
  • 39
0

The is a ternary expression.

It is much more clearly displayed as an if/else, but some people really like them.

useSticks
  • 883
  • 7
  • 15
  • Most people like them because of their small footprint, and inline-ability. – BenM Feb 05 '14 at 16:18
  • Yeah, but they can make easy to understand code very dense when badly used. Style being what it is, I tend to just smile and nod at them. – useSticks Feb 05 '14 at 16:20
0

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.

Tutelage Systems
  • 1,724
  • 1
  • 9
  • 6