What are the PHP operators "?" and ":" called and what do they do?

Viewed 17030

What are the ? and : operators in PHP?

For example:

(($request_type == 'SSL') ? HTTPS_SERVER : HTTP_SERVER)
10 Answers

This is the conditional operator.

$x ? $y : $z

means "if $x is true, then use $y; otherwise use $z".

It also has a short form.

$x ?: $z

means "if $x is true, then use $x; otherwise use $z".

People will tell you that ?: is "the ternary operator". This is wrong. ?: is a ternary operator, which means that it has three operands. People wind up thinking its name is "the ternary operator" because it's often the only ternary operator a given language has.

It's called a ternary operator. If the first expression evaluates to true, HTTPS_SERVER is used, else HTTP_SERVER is chosen.

It's basically a shorthand if statement, and the above code could also be rewritten as follows:

if ($request_type == 'SSL') {
   HTTPS_SERVER;
}
else {
   HTTP_SERVER;
}

This is sometimes known as the ternary conditional operator. Ternary means that it has three arguments, as x ? y : z. Basically, it checks if x is true; if it is, then put y instead of this operation, otherwise z.

$hello = $something ? "Yes, it's true" : "No, it's false";

This is a short way of writing if sentences. It is also used in other languages like Java, JavaScript and others.

Your code,

$protocol = $request_type == 'SSL' ? HTTPS_SERVER : HTTP_SERVER;

can be written like this:

if ($request_type == 'SSL')
    $protocol = HTTPS_SERVER;
else
    $protocol = HTTP_SERVER;

That is a one line if statement:

condition ? true : false

Translated to an ordinary if statement in your case, that would be:

if($request_type == 'SSL') HTTPS_SERVER;
else HTTP_SERVER;

This works like an if statement it's very simple and easy once you get used to it. (conditions_expressions) ? what_to_do_if_true : what_to_do_if_false.

As John T says, it is called a ternary operator and is essentially a shorthand version of an if /else statement. Your example, as a full if / else statement, would read;

if($request_type == 'SSL')
{
    HTTPS_SERVER;
}
else
{
    HTTP_SERVER;
}
Related