Ternário reduced in PHP - Error or misinterpreted?

7

Looking at the manual we have this description:

  

'The expression (expr1)? (expr2): evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.   Since PHP 5.3, it is possible to leave the middle part of the ternary operator. Expression expr1?: Expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise. '

Test

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

Situation

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

    
asked by anonymous 23.04.2015 / 22:05

1 answer

8

I 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)

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

In other words you are returning the result condition 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"
    
23.04.2015 / 22:14