/    Sign up×
Community /Pin to ProfileBookmark

Whats the benefits with {} in strings?

Hi!

I’m learning PHP and I just wondering what the benefits are to use curly braces around variables i strings like:

$fruit1 = “apple”;
$fruit2 = “pineapple”;

echo “This bowl contain one {$fruit1} and one {$fruit2}”;

when this also work:

echo “This bowl contain one $fruit1 and one $fruit2”;

Is it necessary in HEREDOC ?

Thanks!

to post a comment
PHP

11 Comments(s)

Copy linkTweet thisAlerts:
@MindzaiSep 11.2009 — You generally wouldn't use braces in strings just for standard variables as they are unnecessary. The exception being if you want valid variable name characters directly after the variable, as without the braces PHP will think they are part of the variable. For example:

[code=php]
$foo = 'bar';
echo "I like drinking in $foos"; // Notice level error, undefined variable $foos
echo "I like drinking in {$foo}s"; // I like drinking in bars
[/code]


You also tend to see it used for including array elements in strings:

[code=php]
$foo = array('us' => 'bar', 'uk' => 'pub');
echo "I like drinking in $foo['us']s"; // parse error
echo "I like drinking in {$foo['us']}s"; // I like drinking in bars
[/code]


Note that in the above example doing away with the braces and single quotes is also valid:

[code=php]
echo "I like drinking in $foo[us]s"; // I like drinking in bars
[/code]


And no, you do not need to use it in heredoc. The idea with heredoc is that you can enter the text as normal without any messing about with things like braces and escaping quotes etc.
Copy linkTweet thisAlerts:
@pkngauthorSep 11.2009 — Thanks!

But what about this:

$char = (empty($_GET['char']) ? "" : $_GET['char']);

$debug .= "char = [COLOR="Red"]{[/COLOR]$char[COLOR="Red"]}[/COLOR]<br />";

or this:

$form = <<< EOD

<form action='hangman.php' method='get'>

<input type='hidden' name='word' value='{$word}' />

<input type='hidden' name='guessed' value='{$guessed}' />

<input type='text' name='char' />

<button type='submit'>Gissa</button>

</form>

EOD;

or this:

require_once('common.php');

$charset = "iso-8859-1";

$language = "sv";

$title = "H&#228;nga Gubben";

$debug = $debugEnable ? $debug : "";

$html = <<< EOD

<?xml version="1.0" encoding="[COLOR="Red"]{[/COLOR]$charset[COLOR="Red"]}[/COLOR]" ?>

<!DOCTYPE html

PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="[COLOR="Red"]{[/COLOR]$language[COLOR="Red"]}[/COLOR]" lang="[COLOR="Red"]{[/COLOR]$language[COLOR="Red"]}[/COLOR]">


<head>

<meta http-equiv="Content-Type" content="text/html; charset=[COLOR="Red"]{[/COLOR]$charset[COLOR="Red"]}[/COLOR];" />

<title>{$title}</title>

</head>

<body>

[COLOR="Red"]{[/COLOR]$header[COLOR="Red"]}[/COLOR]

<h1>Nya hangman</h1>

<p>Spela nya hangman!</p>

<fieldset>

<div style='float: left'>

[COLOR="Red"]{[/COLOR]$form[COLOR="Red"]}[/COLOR]

</div>

<div style='float: right'>

[COLOR="Red"]{[/COLOR]$svgCode[COLOR="Red"]}[/COLOR]

</div>

</fieldset>

<div style='font-size: small;'>

[COLOR="Red"]{[/COLOR]$debug[COLOR="Red"]}[/COLOR]

</div>

[COLOR="Red"]{[/COLOR]$footer[COLOR="Red"]}[/COLOR]

</body>

</html>

EOD;

Preciate some help?

Thanks!
Copy linkTweet thisAlerts:
@MindzaiSep 11.2009 — It's like I said, the braces are not necessary. It's easy enough to try it and see, the result will be the same with or without braces. They are just unnecessary clutter.
Copy linkTweet thisAlerts:
@pkngauthorSep 11.2009 — OK! I wonder why my teacher use them and whant us to use it in the code?!

Thanks!
Copy linkTweet thisAlerts:
@MindzaiSep 11.2009 — You should ask. Most programmers would agree that the simpler the code the better, so maybe you could make the argument that they are not necessary since you now know when they [I]should[/I] be used and you might even get some credit! Chances are it's just their preference, but the more superflous stuff you place in your code the more chance there is of errors so I would question the idea of teaching you to do so.
Copy linkTweet thisAlerts:
@NogDogSep 11.2009 — It might be a preference for consistency in notation: since the braces may be needed in certain circumstances, using them in [i]all[/i] circumstances would mean that you never have to worry about omitting them when you actually need them. Personally I wouldn't, but some people might. Likewise some people prefer to never have interpolated variables within such strings, but always use concatenation:
[code=php]
$str = "This is a " . $test . ". It is " . $only . " a test.";
[/code]

(In old versions of PHP, the above concatenation style processed faster than interpolated variables, but in modern versions it's really not an issue any more, so it's more a question of style and personal preference.)

I tend to go with interpolated variables in simple cases, and sprintf()/printf() in more complex cases (not that this example is complex):
[code=php]
$str = sprintf("This is a &#37;s. It is %s a test.", $test, $only);
[/code]
Copy linkTweet thisAlerts:
@MindzaiSep 11.2009 — It might be a preference for consistency in notation: since the braces may be needed in certain circumstances, using them in [i]all[/i] circumstances would mean that you never have to worry about omitting them when you actually need them.[/QUOTE]

This is true, but I'm definitely of the "simpler code is best" school of thought. As it doesn't aid clarity and serves no functional purpose I cant see the point in it myself. I'd rather miss the brace the one time I do need it and get the error message then fix it.
Copy linkTweet thisAlerts:
@NogDogSep 11.2009 — This is true, but I'm definitely of the "simpler code is best" school of thought. As it doesn't aid clarity and serves no functional purpose I cant see the point in it myself. I'd rather miss the brace the one time I do need it and get the error message then fix it.[/QUOTE]

If you use an editor that does not have syntax highlighting - or which does but does not differentiate variables within quoted strings - then it would make them stand out more. (Again, it still would not be my preference, but I love to play Devil's Advocate. ? )
Copy linkTweet thisAlerts:
@MindzaiSep 11.2009 — To that I say the solution is to get an editor with syntax highlighting, not write superfluous code! I could fix my itchy finger by lopping off my hand, but the fact that it works doesn't make it a sensible option :p
Copy linkTweet thisAlerts:
@pkngauthorSep 12.2009 — Thanks for all replies!

I use jEdit or Notepad++ to write and edit my code. The both have syntax highlighting with different colors. But I prefer Notepadd++, but with that I can't write code and save it on the server "live"?!

Any other suggestions on nice and free tools for writing and editing code, better than those mention above?

Thanks!
Copy linkTweet thisAlerts:
@NogDogSep 12.2009 — Of the free editors out there that I've tried for PHP, the two I like best right now are Komodo Edit and Netbeans PHP. But ask me again in 6 months and I'll probably have a different favorite. ?
×

Success!

Help @pkng spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...