Ternary Operator

suggest change

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 expr1evaluates 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 http://stackoverflow.com/documentation/php/232/php-types for more information about conversion of variables to boolean.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Operators:
* Ternary Operator

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
33 Operators
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR