HOWTO: get a value from a potential NULL variable or fallback to default constant

This forum covers all minor versions of PHP 7
Post Reply
User avatar
Administrator
Site Admin
Posts: 1725
Joined: Thu Mar 22, 2018 10:19 am

HOWTO: get a value from a potential NULL variable or fallback to default constant

Post by Administrator » Sat Mar 24, 2018 8:10 am

In PHP 7 there is a new way in which you can get a potential value from a variable without adding programming logic in the form of an if statement using the built in isset() function.

previous versions of PHP this would be common place

Code assumes that $example = NULL

Code: Select all

if(isset($example) === TRUE){
	$output = $example;
}else{
	$output = "example is not set";
}


In PHP 7 the same code would look like the following

Code: Select all

$output = $example ??  "example is not set";
The double question mark represents the NULL Coalescing Operator, you could use the NULL Coalescing Operator on as many evaluated values as possible. In the above example as you can see the string literal would always be constant, so in theory we could always use a constant as the final value to make sure that the final evaluated value to the leftmost would always be set.

The following would be valid syntax

Code: Select all

$output = $example ?? (true === true ? NULL : false) ?? NULL ?? NULL ?? NULL ?? "example is not set";

Post Reply