Skip to content
Advertisement

Is it legal omitting braces in inline PHP? [closed]

With braces:

<input type="text" name="text" value="<?php if (isset($text)) { echo $text; } ?>" />

Without braces:

<input type="text" name="text" value="<?php if (isset($text)) echo $text; ?>" />

Both are working fine and give no errors. But out of curiosity, I would like to know which one is the best practice?

Advertisement

Answer

You can safely use such code without adding braces. But only for simple actions like printing something or execute some single command. If your inline PHP code contains more logic you should use braces just because of how this language works.

<!-- This is correct -->
<?php if (isset($text)) echo $text ?>

<!-- Here you have more statements, you should use braces -->
<?php if (isset($text)) { $text = trim($text); echo $text; } ?>

But it’s still better to not create long multi-line statements like this in inline tag. Best practice is transform all required actions before rendering.

<?php
  if (isset($text))
    $text = trim($text);
?>
<!-- Here some other content rendered -->
<?php if (isset($text)) echo $text; ?>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement