tags:

views:

210

answers:

13

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!

A: 

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
+1  A: 

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
`if` is a statement but `?:` is an operator. That’s a difference!
Gumbo
thats true_____
Daniel A. White
+1  A: 

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

Finer Recliner
+2  A: 

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
It’s *a* ternary operator, not “the”.
Gumbo
As Jon Skeet says: 'It's not **the** ternary operator, but **a** ternary operator.'
alex
@Gumbo - stole the words out of my mouth!
alex
I think that should make it all bette.
Thomas Owens
+7  A: 

This is a ternary operator. This basically says

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

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
A: 

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

A: 

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;
}
Dana Holt
A: 

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
+1  A: 

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
+1  A: 

It means exactly this:

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

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