Categories
PHP

Ternary, Elvis, and Null Coalescing Operators

In this tutorial, you’ll learn the usage of Ternary operator, ?: Elvis operator, ?? Null coalescing operator, and ??= Null coalescing assignment operator.

  1. Ternary operator
  2. ?: Elvis operator
  3. ?? Null coalescing operator
  4. ??= Null coalescing assignment operator
  5. Comparing Ternary, Elvis, and Null coalescing operators

Ternary operator

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.

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 the second set (after the question mark). If the first set (condition) is false, the result is the third set (after the colon). See the following example:

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

//2. $a is not defined
$b = isset($a) ? $a : 'default value';
echo $b; //prints "default value"

//3. $a is defined
$a = 'Hello World';
$b = isset($a) ? $a : 'default value';
echo $b; //prints "Hello Word"

The isset function tests if $a is declared and is different than NULL. If true the result will be the second expression $a otherwise the third expression default value.

The above examples are identical to the following if statement:

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

//2. $a is not defined
$b = 'default value';
if (isset($a)){
 $b = $a;
}
echo $b; //default value

//3. $a is defined) 
$a = 'Hello World';
$b = 'default value';
if (isset($a)){
 $b = $a;
}
echo $b; //Hello World

Elvis ?: operator:

What are the question mark and colon symbols in PHP?

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 
$activeUser = isset($a) ? true : false;

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

<?php
//1.            1st        3rd
$activeUser = isset($a) ?: false;
var_dump($activeUser); //false 

//2.
$a = 'Any value that evaluates to TRUE';
$activeUser = isset($a) ?: false;
var_dump($activeUser); //true

This code evaluates the value of the first expression if the first expression is true – otherwise, it evaluates the value of the third expression (the second expression is omitted).

Note: The isset function checks whether a variable is defined or exists, return true if the variable is set, otherwise return false. If you use an undefined variable without testing its existence, the Elvis operator ?: raises an E_NOTICE if the variable does not exist. See the following example:

<?php
 //$a is not defined
 $activeUser = $a ?: false
 var_dump($activeUser);

/*Prints on the browser
Warning: Undefined variable $a in /example.php on line 3
bool(false)
*/

It is recommended to use the null coalescing operator instead of Elvis operator because the null coalescing operator doesn’t raise a notice error if the variable is not set.

?? Null Coalescing Operator

How to use double question ?? marks in PHP?

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 function):

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

PHP 7 introduced “null coalesce operator (??)” to check whether a variable contains a value, or returns a default value. This operator ?? is ideal to use with $_POST and $_GET for getting input from users or URLs. It does not generate any notices if not defined. We can provide the default values if the parameters are not received from user input, the null coalesce operator ?? enables you to write even shorter expressions, see the following example:

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

//or

$page = $_GET['page'] ?? 1;

Channing Null coalesce operator :

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

This will return the first defined value from the expression, the above example can be written without using the null coalesce operator:

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

??= Null Coalescing Assignment Operator

Using double question marks and an equal sign in PHP.

PHP 7.4 added the null coalescing assignment operator ??=. This operator assigns a value to a variable only if the variable is unassigned or undefined:

// Assign value if $name is unassigned
$name ??= 'Guest';

// Same as above
if(!isset($name)) { 
 $name = 'Guest';
}

// Same as above
$name = $name ?? 'Guest';

Ternary ?: vs. ?? Null Coalescing Operator

//Ternary operator shorthand
$user = $_GET['user'] ?: 'Guest';

//Null coalesce operator
$user = $_GET['user'] ?? 'Guest';

The shorthand ternary (Elvis) operator will print Notice: Undefined variable: user... message if $_GET['user'] is not defined.

$a = false ?? 'abcd'; //coalesce
$b = false ?: 'abcd'; //ternary

var_dump($a);
//bool(false)

var_dump($b);
//string(4) "abcd"

If a value exists, the null coalesce operator ?? always returns the first expression while the ternary shorthand operator ?: returns the first expression if the value isn’t equivalent to false.


PHP Control Structures:

  1. If elseif else and Switch Case Conditional Statements
  2. Conditional Expressions
  3. Ternary, Elvis, and Null Coalescing Operators
  4. Using Loops
  5. Using GOTO Operator