views:

87

answers:

4

I'm working on modifying a script to better suit my needs, and I came across this line in the code:

return isset($_COOKIE[$parameter_name]) ? $_COOKIE[$parameter_name] : "";

I know that the function itself is essentially a cookie getter method, but I'm not quite sure what that syntax (i.e. the "?" and ":") means. I apologize if this is a really dumb question, but could someone explain it to me?

+13  A: 

It's a ternary operation and is basically a more compact way of writing an if/then/else.

So in your code sample it's being used instead of having to write:

if (isset($_COOKIE[$parameter_name])) {
    return $_COOKIE[$parameter_name];
} else {
    return "";
}
cherouvim
+2  A: 

The ? : are the ternary operator. Its a very quick if a then b else c:

if (a) { return b; } else { return c; }

is equivalent to:

return a ? b : c;
ck
+6  A: 

It's a ternary operation which is not PHP specific and exists in most langauges.

(condition) ? true_case : false_case

And in my opinion should only be used as short one liners like in your example. Otherwise readabilty would suffer – so never nest ternary operation (though it's possible to do so).

Nils Riedemann
+1  A: 
 return isset($_COOKIE[$parameter_name]) ? $_COOKIE[$parameter_name] : "";

The function return:

$_COOKIE[$parameter_name]

If $_COOKIe with specified parameter_name exists, empty string otherwise.

Prototype:

condition ? this runs if condition true : this runs if condition false;
Sarfraz