PHP

Ternary operator – assign default value to variables

The ternary operator can replace a single if/else clause. Unlike other PHP operators, which work on either a single expression (for example, !$var) or two expressions (for example, $a == $b), the ternary operator uses three expressions. If the first one is evaluated to true, then the second expression is returned, and if it is false, the third one is returned.

PHP ternary operator

  1. Ternary operator
    $user = isset($_GET['user']) ? $_GET['user'] : 'Guest';
  2. Ternary operator shorthand (PHP 5.3)
    $user = isset($_GET['user']) ?: 'Guest';
  3. Null coalescing operator (PHP 7)
    $user = $_GET['user'] ?? 'Guest';

Ternary operator

The ternary operator ?: works with three sets of data:

  1. before the question mark (condition)
  2. after the question mark (before the colon)
  3. after the colon

If the first set (condition) is true then the result is second set (after the question mark). If the first set (condition) is false then result is third set (after the colon). For example:

<?php
$user = isset($_GET['user']) ? $_GET['user'] : 'Guest';

The isset function tests if $_GET['user'] is declared and is different than NULL. If true the result will be second expression $_GET['user'] otherwise the third expression Guest.

The syntax above is identical to the following if statement:

<?php
$user = 'Guest';
if (isset($_GET['user'])){
 $user = $_GET['user'];
}

Elvis operator : ternary operator shorthand

The ternary operator lets your code use the value of one expression or another, based on whether the condition is true or false:

<?php
//              1st          ?     2nd       :   3rd 
$user = isset($_GET['user']) ? $_GET['user'] : 'Guest';

In PHP 5.3 you can now omit the second expression in the list:

<?php
//               1st         ?:   3rd
$user = isset($_GET['user']) ?: 'Guest';

This code evaluates to the value of first expression (condition) if first expression is true – otherwise it evaluates to the value of third expression.

Null coalescing operator

The null coalescing operator ?? is just a special case of the ternary operator. It doesn’t raise a notice error if the variable is not set (and you don’t need to test it with isset):

$user = $_GET['user'] ?? 'Guest';

For more information visit next tutorial : Null coalescing operator ??.

Advertisement:
Advertisement: