I am using a code that I have been left with, but I do not know what this function means:
return $a < $b ? -1 : 1;
I am using a code that I have been left with, but I do not know what this function means:
return $a < $b ? -1 : 1;
It really is not a function. It is an expression that works with a comparison operator ?
called Ternary Operator .
return $a < $b ? -1 : 1;
Its interpretation is similar to this:
// si $a es menor que $b...
if($a < $b) {
return -1;
}
else {
return 1;
}
On the contrary that happens with the if
, where it is habitual and behaves perfectly, it is not recommended to nest or stack several expressions.
$a < $b ? -1 : $c ? -2 : 1;
For such a case, the parentheses should be used to establish preferences and obtain the desired result or opt for a structure with a more evident reading to avoid errors. As for example if
.
It's a compact, simplified if
.
What it does is a check of $a
is less than $b
if it is, returns -1
and otherwise 1
let's say the structure <comparación> ? cierto : falso;
Another way to do it would be like this
$r = 1;
if ($a < $b) $r= -1;
return $r;