What does the "?:" operator mean in PHP? [duplicate]

2

What does the ?: operator mean in PHP?

Example:

$a = 0;

$b = false;

$c = 3;

echo $a ?: $b ?: $c;

Result:

  

3

What exactly is it doing in the above expression?

Is this a ternary? If not, what do you call this operation?

    
asked by anonymous 14.08.2015 / 22:53

2 answers

6

This is the reduced ternary operator , as stated in these answers:

If the condition passes:

$variavel = 10;
$variavel ?: 5; //Irá imprimir 10

If it is 0 , false , NULL or an empty string:

$variavel = NULL;
$variavel ?: 5; //Irá imprimir 5

In other words, the pass condition uses the condition value, it would be the same thing as doing this:

$variavel ? $variavel : 5; //Irá imprimir 5

Source: link

In your example $a is 0 and $b is false , as I said earlier, are values that do not pass in the condition, as explained by @Ricardo and so it ends up going to the $c which is the last value.

Recommendation

It is highly recommended to avoid stacking of ternary expressions. The behavior of PHP when using more than one ternary operator in the single command is not obvious to the interpreter, as you did in your example:

 echo $a ?: $b ?: $c;

So avoid this.

    
14.08.2015 / 23:08
3

This is a ternary operator with the clause for the true result.

Logo: as $a is false enters the second ternary that verifies that $b is true or false and is false enters the false of the second ternary that has $c value.

    
14.08.2015 / 22:57