I am having issue with PHP's ternary operator, since PHP version 5.3 you are able to replace the shorthand ternary operator with an even shorter version
// Older version
$route = isset($test) ? $test : 'test is NOT set';
// Newer version as of 5.3
$route = isset($test) ?: 'test is NOT set';
Now on the newer version, if $test
is not set. it works fine. However when it is set because of the isset()
method, it is returning true
or 1
instead of the value.
Do I have to use the older longer method to get $route
to equal the value of $test
instead of a boolean value of 1
?
You have to use the longer version.
Quoting the docs:
Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
So the correct behaviour for your shorthand version is to return the result of evaluating isset($test)
. Not of $test
as you want.
Starting from PHP 7, you can use the null coalescing operator:
$route = $test ?? 'test is NOT set';
which is equivalent to
$route = isset($test) ? $test : 'test is NOT set';
Here you can find some details:
The null coalescing operator (
??
) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction withisset()
. It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
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