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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With