Ternary operator "?:" [closed]

2

I recently got into a discussion with coworkers about the more compact functionality of the terabyte (x?: 10) and some of them said that it would be removed in php 7. I did a web search and found nothing related to that.

Is there any information on this?

    
asked by anonymous 04.08.2017 / 19:44

1 answer

8

The name of this operator is elvis operator .

It still exists in PHP 7. It may be just a matter of compatibility or even aiming for comfort for those who are already accustomed, but only those who develop the language can respond with certainty.

In PHP 7 there is null coalescing operator ( ?? ) and this operator does the same see edit .

The main difference between them is that null coalesce will not generate a E_NOTICE when the variable is not defined.

$a = null;

print $a ?? 'não há valor';  // Saída: não há valor
print $a ?: 'não há valor';  // Saída: não há valor

print $b ?? 'não há valor';  // Saída: não há valor
print $b ?: 'não há valor';  // Notice: Undefined variable: b 

Edit:

They do not do exactly the same thing, there is an important difference not yet mentioned. The null coalescing ( ?? ) operator evaluates its second expression only if the first expression is null or not yet assigned. Ex.:

null ?? 'Teste'  == 'Teste';

The Elvis operator evaluates the second expression only if the first expression is falsy , that is, a value that, if converted to boolean , has the value false . See this answer with a more detailed explanation. Ex.:

0 ?: 'Teste'  == 'Teste';

Some examples that demonstrate the difference between operators:

null ?: 'Nope' == Nope
null ?? 'Nope' == Nope

'' ?: 'Nope' == Nope
'' ?? 'Nope' == ''

' ' ?: 'Nope' == ' '
' ' ?? 'Nope' == ' '

false ?: 'Nope' == Nope
false ?? 'Nope' == false

0 ?: 'Nope' == Nope
0 ?? 'Nope' == 0

1 ?: 'Nope' == 1
1 ?? 'Nope' == 1

[] ?: 'Nope' == Nope
[] ?? 'Nope' == []

Repl.it with the working code.     

04.08.2017 / 19:49