Change record status: 
Project: 
Introduced in branch: 
9.3.x
Introduced in version: 
9.3.0
Description: 

All usages of isset in ternary operations have been replaced with null coalesce

Before

isset($composerJsonData['require-dev']) ? $composerJsonData['require-dev'] : [];

After

$composerJsonData['require-dev'] ?? [];
Impacts: 
Module developers

Comments

jason_purdy’s picture

Is this a new PHP thing? As of what version?

One of the things that bit me when doing PHP work is that if would sometimes do something like (following your example):

if ($composerJsonData['require-dev']) { ... }

But then PHP would issue a warning sometimes if require-dev wasn't a key in the array already, so I would have to "bulletproof" my PHP code to check for that, too, to eliminate the warning:

if (isset($composerJsonData['require-dev']) && $composerJsonData['require-dev']) { ... }

D9 requires PHP 7.3, so I guess my question for my own understanding is that if you do this, will it generate warnings?

One other concern I have is code readability. Will this increase the reading-level, so to speak, of the underlying code?

jason_purdy’s picture

I wrote a simple test w/ PHP 7.4 to answer my own question and didn't see any warnings:

<?php

$composerJsonData = [];
$foo = $composerJsonData['require-dev'] ?? [];

print_r($foo);
% php ternary-test.php
Array
(
)

Ran this on an older server with PHP 5.6 and that failed, but that's to be expected since it's a new language construction and acceptable since D9 requires PHP 7.3+.

$ php /tmp/ternary-test.php
PHP Parse error:  syntax error, unexpected '?' in /tmp/ternary-test.php on line 4

I also ran this on PHP 7.3 and got the same result as 7.4 without any warnings.

I then updated the script to work with 5.6, just to see the warnings:

<?php

$composerJsonData = [];
$foo = (!$composerJsonData['require-dev']) ? $composerJsonData['require-dev'] : [];

print_r($foo);

Output:

$ php /tmp/ternary-test.php
PHP Notice:  Undefined index: require-dev in /tmp/ternary-test.php on line 4
PHP Notice:  Undefined index: require-dev in /tmp/ternary-test.php on line 4

Anyway, excuse my curious ramblings as I am learning something new (and maybe this may be helpful to others).

krisahil’s picture

Another similar construct is called the "elvis operator" (not sure if that's the official name). I get this operator and null coalescing confused often, but this page has helped me understand them: https://stackoverflow.com/questions/34571330/php-ternary-operator-vs-nul...

osopolar’s picture

Null coalescing operator is part of PHP 7.0. See php.net documentation under "Migrating from PHP 5.6.x to PHP 7.0.x" > Null coalescing operator. This should answer your questions.