After I upgrade PHP from 7.4 to 8.1 this is only a warning that I cannot solve, so I need a little help to correct my function to be in style as the warning show.
public static function ComparePrice($a, $b)
{
return (($a[1] * $a[2]) == ($b[1] * $b[2]) ? 0 : (($a[1] * $a[2]) < ($b[1] * $b[2])) ? 1 : -1);
}
CodePudding user response:
Make it more readable
public static function ComparePrice($a, $b){
$condition1 = ($a[1] * $a[2]) == ($b[1] * $b[2]);
$condition2 = ($a[1] * $a[2]) < ($b[1] * $b[2]);
return $condition1 ? 0 : ($condition2 ? 1 : -1);
}
CodePudding user response:
The ternary operator now needs some more parenthesis. The normal use is (test ? first: second). You nested one in one and missed the right one.
I will re-write your code as follows:
return ( ($a[1] * $a[2]) == ($b[1] * $b[2]) ? 0 : ( ($a[1] * $a[2]) < ($b[1] * $b[2]) ? 1 : -1) );
CodePudding user response:
Fatal error (PHP 8.1.7)
(($a[1] * $a[2]) == ($b[1] * $b[2]) ? 0 : (($a[1] * $a[2]) < ($b[1] * $b[2])) ? 1 : -1);
PHP Fatal error: Unparenthesized `a ? b : c ? d : e` is not supported. Use either `(a ? b : c) ? d : e` or `a ? b : (c ? d : e)`
Make it readable
$cases = [
['a' => 1, 'b' => 1,],
['a' => 0, 'b' => 1,],
];
foreach ($cases as $case) {
$a = $case['a'];
$b = $case['b'];
$aProduct = $a * $a; // $a[1] * $a[2]
$bProduct = $b * $b; // $b[1] * $b[2]
$res = ($aProduct == $bProduct ? 0 : $aProduct < $bProduct)
? 1
: -1;
var_dump($res);
}
Even better to introduce an additional variable: readable and debuggable
...
$tmpRes = $aProduct == $bProduct ? 0 : $aProduct < $bProduct;
$res = $tmpRes ? 1 : -1;
var_dump($res);