Table of Content

PHP ternary operator Examples

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

Syntax

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

Examples

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?