Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isset inline conditions does not work

I am using inline condition to get some value, but I do not understand why it does not return the good value. I want to get false value but it is return test. What I am doing wrong? I have searched in questions but I didn't find why my script does not work. Thanks.

This is the script,

$val1 = null;
$val2 = false;
$val3 = 0;
$val4 = "test";

$newValue = isset($val1) ? $val1 : isset($val2) ? $val2 : isset($val3) ? $val3 : isset($val4) ? $val4 : -1;
var_dump($newValue); // print test
like image 989
cess Avatar asked Mar 16 '26 23:03

cess


1 Answers

You have to surround your tests using braces () :

$newValue = isset($val1) ? $val1 : (
                isset($val2) ? $val2 : (
                    isset($val3) ? $val3 : (
                        isset($val4) ? $val4 :
                            -1
                    )
                )
            ) ;

var_dump($newValue) ; // Outputs : bool(false)

As of PHP 7.0, you could use the null coalescing operator using the ?? characters :

$newValue = $val1 ?? $val2 ?? $val3 ?? $val4 ?? -1 ;
var_dump($newValue) ; // Outputs : bool(false)
like image 131
Syscall Avatar answered Mar 19 '26 13:03

Syscall



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!