php 7 - PHP ternary operator vs null coalescing operator -
can explain differences between ternary operator shorthand (?:) , null coalescing operator (??) in php?
when behave differently , when in same way (if happens)?
$a ?: $b vs.
$a ?? $b
they're same except null coalescing won't output e_notice when have undefined variable.
here's test code:
<?php $a = null; print $a ?? 'b'; print "\n"; print $a ?: 'b'; print "\n"; print $c ?? 'a'; print "\n"; print $c ?: 'a'; print "\n"; $b = array('a' => null); print $b['a'] ?? 'd'; print "\n"; print $b['a'] ?: 'd'; print "\n"; print $b['c'] ?? 'e'; print "\n"; print $b['c'] ?: 'e'; print "\n"; and it's output:
b b notice: undefined variable: c in /in/apaib on line 14 d d e notice: undefined index: c in /in/apaib on line 33 e the lines have notice ones i'm using shorthand terninary operator opposed null coalescing. however, notice, php give same response back.
execute code: https://3v4l.org/mcavc
of course, assuming first argument null. once it's no longer null, end differences in ?? operator return first argument while ?: shorthand if first argument truthy, , relies on how php type-cast things boolean.
so:
$a = false ?? 'f'; $b = false ?: 'g'; would have $a equal false , $b equal 'g'.
Comments
Post a Comment