88
return $add_review ? FALSE : $arg;

What do question mark and colon mean?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57

2 Answers2

174

This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.

Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.

$param = isset($_GET['param']) ? $_GET['param'] : 'default';

There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:

$result = $x ?: 'default';

It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset or a null coalescing operator which is introduced in PHP7:

$param = $_GET['param'] ?? 'default';
Undesirable
  • 353
  • 2
  • 12
Paul Dixon
  • 295,876
  • 54
  • 310
  • 348
  • 18
    Since PHP 5.3, it is also possible to leave out the middle part of the ternary operator. Expression `expr1 ?: expr3` returns `expr1` if `expr1` evaluates to TRUE, and `expr3` otherwise. – Chandrew Dec 17 '14 at 19:15
  • 1
    is there a situation in php7+ where you would want to use `?:` instead of `??`? – user Feb 17 '22 at 22:27
  • @user When `expr1` is not `NULL` but falsy instead (`FALSE`, `0`, etc). – Digitalam Aug 08 '22 at 09:43
22

It's the ternary form of the if-else operator. The above statement basically reads like this:

if ($add_review) then {
    return FALSE; //$add_review evaluated as True
} else {
    return $arg //$add_review evaluated as False
}

See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/

Cristian Ivascu
  • 691
  • 3
  • 4