Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null coalesce operator with casting

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 555
wogsland Avatar asked Jan 23 '16 18:01

wogsland


1 Answers

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

$id = (int) ($_GET['id'] ?? 0);
like image 160
trincot Avatar answered Sep 22 '22 06:09

trincot