user2124857
user2124857

Reputation: 39

Strange ternary operator

<?php echo (isset($var)) ?: $var; ?>

Is this syntax correct? What will this display if $var won't be set, empty string or null? Is it ok to use this?

Upvotes: 0

Views: 167

Answers (7)

Nisarg
Nisarg

Reputation: 3252

<?php (isset($var)) ? echo "" : echo $var; ?>

you can use this one.

Upvotes: 0

deceze
deceze

Reputation: 522024

The syntax is correct, the usage is not. Say here:

$var = something();
echo $var ?: 'false';

This is equivalent to:

$var = something();
if ($var) {
    echo $var;
} else {
    echo 'false';
}

or shorthand for $var ? $var : 'false'.

Your example is pointless since it outputs the result of isset($var) (true) if $var is set and $var otherwise.

You need echo isset($var) ? $var : null or if (isset($var)) echo $var, and there's no shortcut for it.

Upvotes: 1

Sam
Sam

Reputation: 2970

The code no have sense, generates a notice or echo 1, you can't print a $var which isn't set

Upvotes: 0

miszczu
miszczu

Reputation: 1189

This:

<?php echo (isset($var)) ?: $var; ?>

do the same as this:

<?php
 if (isset($var)) {
  // do nothing
 } else {
  echo $var;
 }
?>

So you are trying to display variable if its empty/null/etc...

If function:

<?php $k= (cond ? do_if_true : do_if_false); ?>

$k could be new variable, echo, etc.
cond - isset, $z==$y, etc.

Upvotes: 2

Your Common Sense
Your Common Sense

Reputation: 157839

Nope, this syntax is incorrect.
By the time of echoing, all variables have to be set and properly formatted.
Otherwise means a developer have no idea where their variables come from and what do they contain - a straight road to injection.

So, the proper syntax would be

<?=$var?>

As for the ternaries - I don't like them.

Upvotes: 0

Husman
Husman

Reputation: 6909

This will echo $var either way.

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

So if $var is set, it echos $var (since that evaluates to TRUE), if its not set to anything or evaluates to false, your manually asking it to echo $var anyway.

ideally you want:

(condition  ?  if_true_then_do_this : if_false_then_do_this)

in shorthand this becomes

   (condition ? ? false)

and since you have specified $var in both places, you will get $var, either way. You want this:

echo ($var?:"null");

Upvotes: 0

amphetkid
amphetkid

Reputation: 31

The syntax is fine.

If $var is set then it will output, if it is not, it will throw an Notice about the echo of $var which is unset.

if your error_reporting is set to E_NONE then you will just see a white screen, if the $var is set then you will see the value of $var

Upvotes: 0

Related Questions