What is the function of the operator"??"(two questions) in PHP?

Parsing a script PHP in a certain snippet I came across this line

$valor = $_GET['id'] ?? 1;

What is the interpretation of this code? What does he do?

Author: Maniero, 2017-09-20

2 answers

?? is known as null coalescing was added in PHP 7. Its functionality is to return the first operand if it exists and is not null otherwise it returns the second.

The code in PHP 7

$valor = $_GET['id'] ?? 1;

Can be translated in PHP 5 as

 $valor = isset($_GET['id']) ? $_GET['id'] : 1;

Related:

What does the operator mean"?: "no PHP?

Ternary operator"?: "

What not to do: is it possible use the ternary operator in several conditions simultaneously?

 9
Author: rray, 2018-06-10 00:38:09

The same as in C # and other languages, is the null-coalescing, but since null is a confusing concept in PHP, the check is whether the variable exists. It is the same as writing:

$valor = isset($_GET['id']) ? $_GET['id'] : 1;

I put on GitHub for future reference.

 5
Author: Maniero, 2020-06-16 20:03:00