Table of Content

PHP ternary operator Examples

PHP inherits the ternary operator you might now from C or Perl.


<condition> ? <value on true> : <value on false>


Set variable $query with HTTP GET parameter q or to 'default' if parameter is missing.
$query = isset($_GET['q'])?$_GET['q']:'default';
Multiple defaults: the first non-false value is returned
$result = $input1 ?: $input2 ?: $input3

Use Cases

Why would you want to use the ternary operator?