开发者

need an explanation of return ($a > $b) ? -1 : 1 in php

开发者 https://www.devze.com 2023-03-26 03:24 出处:网络
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:

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


  1. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号