$var= isset($var) and if ( isset($var) ) are same?

$var = isset($var) ? $var="no var";

I saw the code above some days ago in this forum.
I think it is very similar to the code below.

Can I say the code above and the code below work same?

if ( isset($var) ) {
} else {
$var="no var";

Did you try running the script?

Whereabouts did you see the script?

I tried running the script for you and…

The first line of the script produces errors:

Parse error : syntax error, unexpected ‘;’ in /var/www/aatests/joon/joon-003.php on line 6

…so it is pointless trying to compare with the other script;

1 Like

Your first example is incomplete. It is missing the false portion. If it was correct, they are both the same. In Php 7 there is an even cleaner way to do it using the Null Coalescing Operator.


No, because the code above in your post won’t work at all. The ternary operator (the condition ? true-value : false-value construction) wouldn’t allow a variable name where you put one. All you need is the true value after the question-mark, and the false value after the colon.

Barring OP’s incomplete Ternary, If I understand what you are saying, that is not true.

$var = 'nothing';
echo $var = isset($var) ?  $var = 'Sumthing' : $var="no var";

Ah, OK. I’ve never seen it used that way before.

It’s funky and I do not know of a use case. Just pointing out it is possible.

I am so sorry.

The above is wrong.

The below is correct.

$var = isset($var) ? $var : "no var";

The code below is same in result with the code above.
We call the code below as “if-else conditional”.
How would you call the code above? Variable conditional or something?

if ( isset($var) ) { } else { $var="no var"; }

Best explanation is from the Free PHP Online Manual - that has all alternatives in the right-hand menu:


or the simple version:

It is called a Ternary Operator

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.