Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this syntax in PHP?

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?

like image 218
cLuuLess Avatar asked Dec 30 '25 07:12

cLuuLess


2 Answers

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 "";
}
like image 101
cherouvim Avatar answered Jan 02 '26 00:01

cherouvim


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).

like image 41
nocksock Avatar answered Jan 01 '26 23:01

nocksock