PHP syntax question: what does the question mark and colon mean?

Possible duplicate:
php syntax quick question

return $add_review ? FALSE : $arg; 

What does the question mark and colon mean?

thank

+54
syntax ternary-operator php
Aug 14 '09 at 9:27 a.m.
source share
2 answers

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

Think of it as an "if" expression that you can use in expressions. It can be very useful when creating short assignments that depend on some condition, for example.

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

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

 $result = $x ?: 'default'; 

It is worth noting that the above code when using the $ _GET or $ _POST variable will cause an undefined index notification and prevent the need for a longer version with isset or the zero coalescence operator , which is introduced in PHP7:

 $param = $_GET['param'] ?? 'default'; 
+108
Aug 14 '09 at 9:27 a.m.
source share

This is a triple form of the if-else statement. The above statement is mainly read as follows:

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

More about trernary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/

+14
Aug 14 '09 at 9:34
source share



All Articles