Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newer style PHP ternary operator has undesired result with isset function

Tags:

php

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 ?

like image 540
JasonDavis Avatar asked Dec 20 '11 02:12

JasonDavis


2 Answers

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.

like image 148
Juan Avatar answered Oct 07 '22 09:10

Juan


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 with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

like image 43
ROMANIA_engineer Avatar answered Oct 07 '22 10:10

ROMANIA_engineer