Home > OS >  Is it legal omitting braces in inline PHP?
Is it legal omitting braces in inline PHP?

Time:10-22

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?

CodePudding user response:

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; ?>

CodePudding user response:

It is legal to use without braces for single line actions. The statement right next to the if will be considered as the body of the condition.

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

For multiline actions, braces are compulsory. I prefer it is always better to use the braces to avoid confusions in future.

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

Otherwise you can use the colon and end for both single line and multiline statements as below:

if(a < 1 ) :
    echo "a is less than 1";
    echo "a=" a;
endif;

CodePudding user response:

Better practice to use short one for output:

<?= $output ?? null; ?>

And in multi lines / complex logic

<?php
$output = null;
if ($condition) {
    $output = 1;
    //some code
    if ($anotherCondition) {
         $output = 2;
    }
}
?>

And in input

<input type="text" name="text" value="<?= $output ?>" />

This will keep code clean and supportive for future developers :)

  •  Tags:  
  • php
  • Related