Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

return

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

like image 994
Edmund Rojas Avatar asked Jan 26 '26 05:01

Edmund Rojas


2 Answers

  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)

like image 65
Shef Avatar answered Jan 28 '26 17:01

Shef


? 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
like image 33
Petar Minchev Avatar answered Jan 28 '26 18:01

Petar Minchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!