Brackets in PHP double-quoted strings [closed] - php

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
this is more of a better-practice type of question.
I'd like to know if using brackets in double-quoted strings for variables is good practice.
For example:
<?php
$Variable = 'a variable';
$SingleQuotedString = 'Single quoted string with ' . $Variable;
// Single quoted string with a variable
$DoubleQuotedString = "Double quoted string with $Variable";
// Double quoted string with a variable
$DoubleQuotedStringWithBrackets = "Double quoted string with {$Variable} in brackets.";
// Double quoted string with a variable in brackets.
?>
It doesn't change the output or the code from simple tests, and obviously works. I'm just confused because not many people do this, and I don't see recommendations or people disagreeing with it, and I've been using them just fine.
Thanks for any feedback!

The curly braces are to allow the use of arrays and objects, i.e:
$string = "my array value: {$foo['bar']}";
or
$string = "my object value: {$foo->bar}";

Fastest and cleanest version is the first one. Variables in a double quoted string... just don't "feel" right to me.
$SingleQuotedString = 'Single quoted string with ' . $Variable;
The only situation where it comes in handy I can think of is when you have a
$string = "with a {$load} of {$variables} in {one} {sentence}!";
and the readability would suffer to much otherwise.

You need to use brackets in case you have no space after your variable
$a = 1;
$aa = 2;
echo "$aaa"; // prints nothing but a notice cause $aaa is not defined
echo "{$a}aa"; // prints 1aa
echo "{$aa}a"; // prints 2a
or if you want to call an object method
echo "{$myObject->myMethod()}"; // fatal error cause $myObject is null ;) otherwise it works just fine
Otherwise you can use brackets or not.
Single quotes are faster if you have no variables in your string.
Accessing array value or object propertie does'nt require brackets. But maybe it's a bit easyer to read.

The real reason that bracket quoted variables in strings exists is for accessing values in arrays or objects. E.g.
echo "The result is {$res['foo']}"
or
echo "The result is {$res->foo}"
which won't work if you didn't use the brackets. If you find it easier to see bracket quoted strings then use them. If not then use them only when required (to dereference an array or object).

These are all stylistic choices because so long as you follow the rules you'll end up with the same result. You're trading off readability, editability, error-resistance and a truly tiny amount of speed with each one. There are no accepted 'best practices', but simply developer preferences which people will defend zealously.
I find the single quote form noisy, more verbose and less aesthetically pleasing. I tend to use it only for short strings.
I prefer double quotes for longer strings, because they give me the flexibility to move interpolations around the string in an less error prone way. I use brackets when I must be
explicit or need the value inside an array or object, but always err on the side of succinctness.
In general it's probably best to just be consistent to maximize team productivity.

Related

What's better to use: ' or " [duplicate]

This question already has answers here:
What is the difference between single-quoted and double-quoted strings in PHP?
(7 answers)
Closed 7 years ago.
What is better to use in PHP?
' or "? for something like this:
<?=$json["response"]["players"][0]["personaname"];?>
And this:
$steamid = "";
"Better" really depends on your use cases. In both your example, the single quote is better for the perfomance because you have no $variable interpolation needed.
Otherwise "better" may be a question of style (and a little of performance).
Read the documentation for more : http://php.net/manual/en/language.types.string.php
Better? Well, let's just say that an empty string with single quotes is the most basic string literal you can use. In your example shown, I would use single quoted strings for array elements and the empty string. PHP will know that the string literal is only a string literal, and that nothing else needs to be "interpolated." Better? Who knows.
One place to use "" is with escape sequences such as "\n" .

single quotes or not in square bracket data?

I have a (probably) very simple and easy to answer question, which I cannot find the answer to anywhere, perhaps it is too simple, and I am not well-versed in php.
I am using a script written by someone else, and they sometimes use single quotes within the square brackets, [ ], and sometimes not. What is the correct way?
For example, is it best written [data] or ['data']? I am a perfectionist and this is driving me crazy to know the proper method.
Echo "Name: " .$ratings['name']."";
$current = $ratings[total] / $ratings[votes];
Echo "Current Rating: " . round($current, 1) . "";
You must always use single or double quotes when accessing an array element.
I asked in ##php on freenode, and they believe this quirk existed since PHP4.3 (god knows why), but right now when PHP comes across $array[value], it firstly tries to look for a constant named value, and if it is not define()'d, it treats the expression as $array["value"] and spit a Notice in PHP4. In PHP5, this has been upgraded to a warning.
In short: Don't use it. It confuses yourself.
Definitely use the quotes. Additionally, there is a subtle but important difference in PHP between single and double quotes strings. A single quoted string is actually faster, because it is treated as a literal, whereas a double quoted string gets interpreted, which takes O(n) time. Example:
$test = 'world';
echo 'hello\n$test';
yields hello\n$test
$test = 'world';
echo "hello\n$test";
yields
hello
world
Either double or single would work. Personally I prefer single.
PHP is very forgiving and only spits out a notice if no quotes are given to an index of the array.

Whats the difference between these codes [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am a beginner in PHP and trying to learn and want to know the difference between these codes:
echo "<div>$lang[CATEGORY_NAME]</div>";
echo "<div>" . $lang['CATEGORY_NAME'] . "</div>";
and when I should use each one.
Ill split my answer into 3 parts.
1. Double quotes string
In other words code like
echo "foo lol";
In double quotes string the PHP interpreter look for variables inside the string, and replaces them with their value. So the following code
$lol = "how are you";
echo "foo $lol";
will produce the following output.
foo how are you
Note that in double quoted string, the PHP interpreter will always look for variable and will replace them with their value, even if there are no variables in the string (this can cause performance issue, but later on this).
2. Single quoted string
i.e. code like
$lol = 'hello';
echo '$lol user';
In this case, PHP interpreter outputs the string as is. So if you did not guess yet, the output will be
$lol user
(see the $lol was not replaced by its value, in this case $lol is just a string that start with the dollar sign (not a variable).
3. String concatenation
As the name implied, used to concatenate string. The special PHP character . (dot) used to concatenate strings, for example
$lol = 'hello';
$bar = 'user';
echo $lol . ' ' . $bar . '. How are you?';
And the output will be
hello user. How are you?
Performance and usage
Now to the answer. As I said already, double quoted string will look for variables in them, so if you do not plan to output variable inside string, its always faster to use single quoted strings.
As for outputting variables, its always better to concatenate them with single quoted string as opposed to use double quoted strings.
See the following example:
echo "Hello {$arr['var1']['var2']}. How are you?";
This code is unclear, and it might cause problems when you want to output string that contains quotes in them and etc. Also as you noted (thanks for Martina comment), if you want to output arrays with keys, you have to surround them with { and }, so variable inside double quoted strings are a mess to read.
This code
echo 'Hello ' . $arr['var1']['var2'] . '. How are you?';
Is more readable, and faster in parsing.
Hope this answers your question :)
echo '<div>' . $lang['CATEGORY_NAME'] . '</div>';
This has the advantage of not searching for variables inside quotes (use single quotes otherwise parser has to check for variables in the string).
The variable inside double comma string is variable. So when the code is parsed it is treated as variable. In the later example you are concatinating the string with $variable. the later method should be used because it gives clear readness and take less time to parse the code.
Another thing is that you can use single commas for the later example and double commas for first example. But separating $variables from string and using concat is a good practice.
Single Comma with variable
Example :
echo '<div>$lang[CATEGORY_NAME]</div>';
Output
<div>$lang[CATEGORY_NAME]</div>
Single Comma with concat
echo '<div>' . $lang['CATEGORY_NAME'] . '</div>';
Output
Category_name // whatever
Double Comma with variable
Example :
echo "<div>$lang[CATEGORY_NAME]</div>";//parser will search for variable inside string
Output
Category_name // whatever
Double Comma with concat
echo "<div>" . $lang['CATEGORY_NAME'] . "</div>";
Output
Category_name // whatever
Now it's up to you what you want to choose.
When PHP meets double quotes ", it performs a string scanning to evaluate any variable that may have been mentioned inside (at runtime), that needs to be evaluated. Unlike ", single quotes ' make PHP use the string as is, without further evaluation and is therefore faster.
In this case,
echo '<div>' . $lang['CATEGORY_NAME'] . '</div>';
is slightly better as the <div> and </div> tags won't need any more evaluation from PHP. Additionally, PHP can perform some optimization with $lang['CATEGORY_NAME'] as it flags what it is at compilation time (thanks to APC, compilation is done only once after the script file changes).
In the first case
echo "<div>$lang[CATEGORY_NAME]</div>";
the string is parsed at runtime, and is therefore slightly more expensive than the above version.

php general question

Hey i was looking through some of WP's code and I noticed in certain cases between double quotes, they put curly brackets around the variable. Here is an example:
$templates[] = "header-{$name}.php";
I tried looking online, but found it difficult to search for this. Would anyone be able to explain the use of this / benefits?
Much appreciated.
http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double
Scroll way down to the part on variable parsing for a detailed explanation.
Basically, inside a double-quoted string, PHP with replace variables with their contents.
$var = 'pig';
echo "Hello, $var"; // echos Hello, pig
Wrapping the variable in curly braces allows you to access associative arrays, object members, functions, etc ("{$var['key']} {$foo->bar} {${$foo->baz()}}"), and makes your code a little more readable (imho)
It mainly allows you to specify things like arrays. An example would be:
$arr = array("mon"=>"Monday","tue"=>"Tuesday");
echo "Today is {$arr["mon"]}";
It has its place, but doesn't need to be used with the example above. Some people prefer it (to help them tell the variables from the string), and some prefer to just use single quotes with concatenation.

Single quotes or double quotes for variable concatenation? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Is it better to concatenate a variable (say, $name) into an existing string (say, $string) like this:
$string='Hi, my name is '.$name
or to embed the variable in the string like this:
$string="Hi, my name is $name";
or is it better to use a function like this:
$string=sprintf("Hi, my name is %s",$name);
Which is better in terms of processor time/efficiency?
Everyone who did the test concluded that using single quotes is marginally better performance wise. In the end single quotes result in just a concatenation while double quotes forces the interpreter to parse the complete string for variables.
However the added load in doing that is so small for the last versions of PHP that most of the time the conclusion is that it doesn't really matter.
So for the performance people: use single quotes. For the "i like my code readable"-people: double quotes are a lot better for the legibility, as Flavius Stef already pointed out.
Edit: One thing though - If you are going to use a a single dollar in your string without a variable, use single quotes for sure! (http://www.weberdev.com/get_example-3750.html points out that it will take 4 times longer to parse those strings)
The difference between single and double quotes in PHP is that double quotes are "intelligent" in that they will parse for variables when being read, while single quotes are "dumb" and will not try to parse any character in the string.
These result in some minor differences in what characters you can use; basically, the only character you need to escape when using single quotes is a single quote itself:
'\''
While if you use double quotes you have to escape other characters:
"\$"
But it also allows for some nifty things like adding a new-line to the end:
"my string\n"
With single quotes you would have to do a concatenation:
'my string' . chr(10)
'my string' . "\n"
Generally, single quotes are faster because they are "dumb".
However, normally one should not really worry about these issues, that is called Premature optimization, and should be avoided.
A couple of words about optimization: generally one should first write the program the way it should work, and then find the biggest bottlenecks and fix those particular ones. If string speed really is an issue for you in PHP, you might want to consider switching to another language.
Regarding speed: you probably want to focus more on memory usage than on CPU time. In these cases the CPU time could be considered pretty constant. CPU time is more relevant when writing algorithms that will iterate many times.
Regarding concatenations: the more you concatenate strings using the dot-operator, the more memory you will be using.
Consider this:
$str1 = 'asdf';
$str2 = 'qwer';
// this will result in more memory being allocated for temporary storage
echo $str1 . $str2;
// this will not allocate as much memory as the previous example
echo $str1;
echo $str2;
I generally feel that using string interpolation ("Hi, my name is $name") is better from a legibility standpoint.
For performance, as others have proven, it is marginally faster to use single quotes rather than double quotes.
Single quotes, if applied to readability science and kept away from subjectivity actually adds more "noise". Noise and how it relates to readability is talked a lot about in the book Clean Code and one could conclude that the more non-whitespace you have to see, the more it hinders readability. If applied to subjectivity, most places that I've taken the time to read actually prefer single over double quotes.
Use your judgement.
$var = "My $string with $lots of $replacements."
Is much more readable than:
$var = 'My ' . $string . ' with ' . $lots . ' of ' . $replacements . '.';
I'll admit that:
$var = "My string.";
Looks almost the same as:
$var = 'My String.';
However the latter introduces less noise and when there's lots of code around it every little bit helps, not to mention the other benefits you get from using single quotes.
In the end, I prefer to KISS. Use single quotes unless you need double quotes. Simple convention that is easier to type, easier to maintain, easier to parse and easier to read.
It doesn't matter from syntax perspective. Both variants are correct. Use what you feel more comfortable.
Personally, I feel better when using the $string="Hi, my name is $name", because you don't need to mess with quotes. Just image the complex SQL query with, let's say, 10 variables...
PHP is pretty slow:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-088-introduction-to-c-memory-management-and-c-object-oriented-programming-january-iap-2010/lecture-notes/MIT6_088IAP10_lec01.pdf
Slide #3
So don't worry too much about little optimizations like these.
Focus more on using APC to cache your code into byte code though. You'll see big speed gains for the project.
Personally, if it's just a normal variable, or even a class property, I'd write it like this:
$newVarA = "This is some text with a $variable";
$newVarB = "This is some more text, written in $settings->language";
However, if I'm using array values then I'll concatenate with single quotes.
$newVarC = 'This is some text from a ' . $text['random'] . ' array';
Hope this makes sense. It's all about finding convention and sticking to it.
My motto and answer is: Leave it to the compilers to write machine code. I will tell you what I mean...
Use single quotes when you don't need to include PHP variables, otherwise use double quotes.
Dont bother about performance just use APC on production servers. Instead focus on writing the most maintainable code; use comments, double quotes etc. properly even though they may slow code down. Every optimization that decreases maintainability / readability of code is bad, leave it to the opcode-cachers and compilers to turn your code into machine code, don't do it yourself... obfuscating your source code because of optimization fires back.
The single quoted string is better option than double quoted string while concatenating the variables.
click the link for better understanding...
http://www.codeforest.net/php-myth-busters-using-single-quotes-on-string-is-faster-then-double-quotes
$string='Hi, my name is '.$name
This is the best way, in the sense of php and html combination!
or like this:
$string="Hi, my name is $name";
This is the old way!
Or like this:
$string=sprintf("Hi, my name is %s",$name);
This is what a programmer coming from Visual Basic or other Client Programming languages would write!
I hope I was helpful.

Categories