The ternary operator can be thought of as an inline if
statement. It consists of three parts. The operator
, and two outcomes. The syntax is as follows:
$value = <operator> ? <true value> : <false value>
If the operator
is evaluated as true
, the value in the first block will be returned (<true value>
), else the value in the second block will be returned (<false value>
). Since we are setting $value
to the result of our ternary operator it will store the returned value.
Example:
$action = empty($_POST['action']) ? 'default' : $_POST['action'];
$action
would contain the string 'default'
if empty($_POST['action'])
evaluates to true. Otherwise it would contain the value of $_POST['action']
.
The expression (expr1) ? (expr2) : (expr3)
evaluates to expr2
if expr1
evaluates to true
, and expr3
if expr1
evaluates to false
.
It is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3
returns expr1
if expr1
evaluates to TRUE, and expr3
otherwise. ?:
is often referred to as Elvis operator.
This behaves like the Null Coalescing operator ??
, except that ??
requires the left operand to be exactly null
while ?:
tries to resolve the left operand into a boolean and check if it resolves to boolean false
.
Example:
function setWidth(int $width = 0){
$_SESSION["width"] = $width ?: getDefaultWidth();
}
In this example, setWidth
accepts a width parameter, or default 0, to change the width session value. If $width
is 0 (if $width
is not provided), which will resolve to boolean false, the value of getDefaultWidth()
is used instead. The getDefaultWidth()
function will not be called if $width
did not resolve to boolean false.
Refer to Types for more information about conversion of variables to boolean.