2

Possible Duplicate:
What is the PHP ? : operator called and what does it do?

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

Can someone help me understand the above code? I'm fairly new to php :) What up with ? and :?

I would appreciate it!

Community
  • 1
  • 1

13 Answers13

7

This is a ternary operator. This basically says

if(isset($_GET['id']))
{
   $id = intval($_GET['id']);
}
else
{
   $id = 0;
}
scheibk
  • 1,370
  • 3
  • 10
  • 19
2

That is a ternary operator.

What is says that is if $_GET['id'] is set, $id is intval($_GET['id']), otherwise, $id is 0.

Thomas Owens
  • 114,398
  • 98
  • 311
  • 431
1

The ? and : are parts of an inline if.

Basically, if isset($_GET['id']) is true, intval($_GET['id']) is used. Otherwise, $id gets 0.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
1

x ? y : z = if x is true then y else z

Finer Recliner
  • 1,579
  • 1
  • 13
  • 21
1

That’s the conditional operator :

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
1

It means exactly this:

$id = 0;
if(isset($_GET['id'])) {
    $id = intval($_GET['id'];
}
karim79
  • 339,989
  • 67
  • 413
  • 406
0

This is short notation for an if. The notation is taken from C.

It could be re-written:

if (isset($_GET['id']) ) {
     $id = intval($_GET['id']);
} else {
     $id = 0;
}
acrosman
  • 12,814
  • 10
  • 39
  • 55
0

Its called a ternary

it populates $id with intval($_GET['id']) if isset($_GET['id']) returns true else it will populate it with 0

AutomatedTester
  • 22,188
  • 7
  • 49
  • 62
0

see: http://www.lizjamieson.co.uk/2007/08/20/short-if-statement-in-php/ and http://php.net/operators.comparison

Mat
  • 202,337
  • 40
  • 393
  • 406
b0x0rz
  • 3,953
  • 8
  • 52
  • 82
0

If $_GET['id'] exists it sets $id = $_GET['id'], if not it sets $id = 0, it uses ternary. http://uk3.php.net/ternary

0

This is just shorthand for an if statement (ternary operator) and is the same as:

if (isset($_GET['id']))
{
    $id = intval($_GET['id']);
}
else
{
    $id = 0;
}
TWA
  • 12,756
  • 13
  • 56
  • 92
0

That's a ternary operator. Basically, it has a

if (condition) {

} else {

}

in one line.

The code says

If the GET var id has been set, then set the $id var to equal the integer of the GET's variable.

For arguments sake too, casting with (int) has been proven to be much faster.

alex
  • 479,566
  • 201
  • 878
  • 984
0

That statement essentially means this:

$id = 0;

if (isset($_GET['id']))
{
    $id = intval($_GET['id']);
}
else
{
    $id = 0;
}

The ?: operator means "if condition then result else other_result," all in one line. You're basically setting the value of the $id variable based on a boolean (true/false) condition. If the condition is true, the first result is used to set the value of the $id variable. Otherwise, it uses the second value.

Tim S. Van Haren
  • 8,861
  • 2
  • 30
  • 34