Reduced ternary in PHP - Error or misinterpreted?

Asked

Viewed 198 times

7

Looking at the manual we have this description:

'The Expression (Expr1) ? (expr2) : (expr3) evaluates to expr2 if Expr1 evaluates to TRUE, and expr3 if Expr1 evaluates to FALSE. Since PHP 5.3, it is possible to Leave out the Middle part of the Ternary Operator. Expression Expr1 ?: expr3 Returns Expr1 if Expr1 evaluates to TRUE, and expr3 otherwise.'

Testing

$vlTeste1 = 5.25;
var_dump($vlTeste1 > 0 ?: 9.99); // true , em vez de 5.25

Situation

According to the description, this incorrect do $vl = (!empty($vl)) ?: null; ?

  • but sure it will return to Expr1 which is ($vlTeste1 > 0) which is a true bool

1 answer

8


Would return 5.25 if you did so:

var_dump($vlTeste1 ?: 9.99); //Retorna float(5.25)

If you do

var_dump($vlTeste1 > 0 ?: 9.99); //Retorna bool(true) ou float(9.99)

He will return the $vlTeste1 > 0 and not the $vlTeste1, therefore $vlTeste1 > 0 is a condition the result is boolean and for this reason in your case returned TRUE.

In other words you are returning the condition result and not the variable.

Note: 0 and NULL if not used with "identical" comparisons (for example ===) will be equivalent to false, for example:

var_dump(NULL ?: 'foo'); //Retorna string(3) "foo"
var_dump(0 ?: 'foo'); //Retorna string(3) "foo"
  • 1

    In the second example it returns bool(true) or float(9.99)

  • @Adirkuhn truth

Browser other questions tagged

You are not signed in. Login or sign up in order to post.