0

This code works in PHP 7.x

$array = ['asda' => ['asdasd']];
$var = $array['asda']['asdasd'] ?? "yes!";
echo $var;

If we replace ?? with ?: as we have in older PHP version, this code will not work, for example:

$array = ['asda' => ['asdasd']];
$var = $array['asda']['asdasd'] ? $array['asda']['asdasd'] : "yes!";
echo $var;

It means, we will get an error like: Notice</b>: Undefined index: asdasd in <b>[...][...]</b> on line

So, can we use the first example in PHP 7.x without afraid about anything strange/unexpected in behind? I mean, is it safe to use this instead, for example, array_key_exists or isset

Kolesar
  • 1,265
  • 3
  • 19
  • 41
  • 2
    http://php.net/manual/en/migration70.new-features.php please refer this like, this is an new feature in 7.x *Null coalescing operator* yes it safe. – Kmg Kumar Oct 05 '18 at 05:32

1 Answers1

1

Use isset() to test if the element exists.

$var = isset($array['asda']['asdasd']) ? $array['asda']['asdasd'] : "yes!";

The old :? conditional operator is a simple if/then/else -- it tests the truthiness of the first expression, and then returns either the second or third expression depending on this. The test expression is executed normally, so if it involves undefined variables, indexes, or properties you'll get a normal warning about it.

The new ?? null-coalescing operator, on the other hand, tests whether the first expression is defined and not NULL, not just whether it's truthy. Since it does it's own check for whether the expression is defined, it doesn't produce a warning when it's not. It's specifically intended as a replacement for the isset() conditional.

See PHP ternary operator vs null coalescing operator

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 2
    You might want to point out what the difference between the two operators `?:` and `??` is, so the op understands better as to why his code isn't working as intended. – Tobias F. Oct 05 '18 at 05:43
  • 1
    Thanks, I've added some explanation, along with a link to a related question. – Barmar Oct 05 '18 at 14:35