A bit of a silly question for more advanced programmers, but In my quest to learn php I have come across return statements that involve a ? symbol with values of 0, -1 and 1 such as:
return ($a > $b) ? -1 : 1;
or
[$index ? 0 : 1];
Im trying to understand the logic of what this statement does and why it is used, any help will go a long way, thanks
return ($a > $b) ? -1 : 1;If $a is greater than $b return -1, else return 1.
It is the ternary operator (a.k.a shorthand if/else statement)
? is the ternary operator. If the boolean expression ($a > $b) is true then -1 is returned else 1 is returned. It is just a short if else combination.
To summarise boolean expression ? x : y is equal to:
if (boolean expression)
evaluates to x
else
evaluates to y
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With