Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The new PHP7 "null coalescing" operator gives an Undefined index notice? [duplicate]

I have upgraded to PHP 7 and started using the null coalesce operator to convert things like

$email = isset($_SESSION['email']) ? $_SESSION['email'] : '';

to

$email = $_SESSION['email'] ?? '';

but I can't figure out how to do this if I am casting as well. For example, the for the old statement

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

I would think something like

$id = (int) $_GET['id'] ?? 0;

should work, but it doesn't appear to in the sense that, if $_GET['id'] is not set, $id resolves to 0 but I get the Notice

Notice: Undefined index: id in test.php on line 2

like image 519
wogsland Avatar asked Jan 23 '16 18:01

wogsland


People also ask

What is the null coalescing operator in php7?

In PHP 7, a new feature, null coalescing operator (??) has been introduced. It is used to replace the ternary operation in conjunction with isset() function. The Null coalescing operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

How do I fix Undefined index in PHP?

Undefined Index in PHP is a Notice generated by the language. The simplest way to ignore such a notice is to ask PHP to stop generating such notices. You can either add a small line of code at the top of the PHP page or edit the field error_reporting in the php. ini file.

How can we prevent Undefined index?

The error can be avoided by using the isset() function. This function will check whether the index variables are assigned a value or not, before using them.


1 Answers

The (int) cast gets precedence over the ?? operator, so use brackets:

$id = (int) ($_GET['id'] ?? 0);
like image 184
trincot Avatar answered Oct 09 '22 00:10

trincot