need an explanation of return ($a > $b) ? -1 : 1 in php
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 lon开发者_运维百科g 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
It's same like
if ($a > $b)
return -1;
else
return 1;
(It's shorthand)
Search for "ternary" on this page
Isn't it similar to C's if statement but in one line? So I thought this is the PHP equivalent:
if ($a > $b) {
return -1;
} else {
return 1;
}
Whilst the short hand version would be:
return (($a > $b) ? -1 : 1);
So what you're having is something like this:
(if true) ? then : else;
Check out this for more details.
精彩评论