2
What the operator means ?:
in PHP?
Example:
$a = 0;
$b = false;
$c = 3;
echo $a ?: $b ?: $c;
Upshot:
3
What exactly is he doing in the expression above?
Is that a ternary? If not, what do you call this operation?
2
What the operator means ?:
in PHP?
Example:
$a = 0;
$b = false;
$c = 3;
echo $a ?: $b ?: $c;
Upshot:
3
What exactly is he doing in the expression above?
Is that a ternary? If not, what do you call this operation?
6
This is the operator reduced ternary, as stated in these replies:
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 passing condition then uses the value of the condition, it would be the same thing as doing this:
$variavel ? $variavel : 5; //Irá imprimir 5
Source: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.Ternary
In his example $a
is 0
and $b
is false
, as I said earlier, are values that do not pass in condition, as explained by @Ricardo and so ends up going to the $c
which is the ultimate value.
It is highly recommended to avoid the "Stacking" of ternary expressions. PHP’s behavior 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.
Guilhermenascimento Good answer
Man, interesting that the interpreter, did not know. for me this was equal that expression in javascript var x = x || 0
@Wallacemaxters does exist a ? a : b
in javascript as well, but there is no a ?: b
@Guilhermenascimento, what I meant is that the effect is the same
@Wallacemaxters a yes understood, is the effect is the same, note that in php this $x || 0;
it’s also possible. I really don’t see the difference between the two in the end result. (it would serve as a good question for you to formulate, something like, what the advantage of the reduced suit or what is the difference between ?:
and ||
) - See you around
3
That’s a ternary operator with the clause aimed at the result true emptiness.
Hence: how $a
is phony enters the second suit that checks whether $b
is true or false and is phony enters the clause false of the second ternary which has the value of $c
.
Browser other questions tagged php operators
You are not signed in. Login or sign up in order to post.
Related http://answall.com/q/56830/101 and http://answall.com/q/56812/101 and http://answall.com/q/44133/101
– Maniero
Duplicate or related? Operations are different in this case, no?
– Wallace Maxters