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.
Related
I am new to Laravel and I am having this question.
I tried out this line of code and it works fine: return redirect("/cards/{$note->id}");
But when ever I try to use the single quotes, it does not work: return redirect('/cards/{$note->id}');
How can I solve this problem ?
What you are doing first is called variable interpolation or string interpolation. You can read more about it here, on PHP docs and here, on Wiki.
It's a feature in PHP that allows you to pass a string and have variables/placeholders inside interpreted.
In your second example you are using single quotes, which does not provide this feature, so you will have to break it up and add the variable manually to the string:
return redirect('/cards/' . $note->id);
If you are interested in a more elaborate explanation and the performance behind it then you can read more on this answer here by Blizz
He concludes that:
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.
You should use "/cards/{$note->id}" or '/cards/'.$note->id
The most important feature of double-quoted strings is the fact that variable names will be expanded.
When a string is specified in double quotes or with heredoc, variables are parsed within it.
From PHP documentation
Use it like that:
return redirect('/cards/'. $note->id);
With either single or double quotes
I'm looking for a function in PhpStorm that transform the string like:
echo "my string: $var1, $var2, $var3";
into something like that:
echo 'my string: '.$var1.', '.$var2.', '.$var3';
Thanks in advance
First we have to do a little phpstorm setup.
Settings > Editor > General > Smart Keys
Please mark this. "Surround selection on typing quote or brace"
Click OK.
Then select the entire code with double quotes. Now press the single quotation key.
Done.
Install "PHP 1Up!" plugin and restart IDE.
Now you will have new intention available (accessible via Alt + Enter or via light bulb icon):
UPDATE 2022-12-28:
The similar functionality is now implemented in PhpStorm itself (for a few years now). The intention is called "Convert string interpolation to concatenation". The downside is it will not replace double quotes into single, this will have to be handled separately.
Although I personally highly prefer "Convert string interpolation to a 'sprintf()' call" one instead -- why use concatenation at all for such a stuff? Any kind of templating is always better (especially for making edits in the future):
easier to add more stuff;
easier to wrap those variables into a function calls (e.g. escaping/cleanup/formatting etc);
easier to make translations (if needed of course);
the string (template) can be taken from elsewhere (a config file/DB) etc.).
Sure, sprintf() is slower than just an echo with a bunch of concatenations, but it is much more convenient to use.
The result of the above:
echo sprintf("my string: %s, %s, %s", $var1, $var2, $var3);
As others have already mentioned:
no noticeable speed gains
for possibly better readability, surround variables with {}, e.g. echo "my string: {$var1}, {$var2}, {$var3}";
No way. You can explode it in concatenation by hands and then convert quotes:
With internal 'Replace quotes' action
Regexp find/replace
String manipulation plugin
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.
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.
I have an issue here, and I'm looking for experienced programmers to tell me which is the preferred solution.
I have values being returned that are surrounded in quotes. "TOTAL" and "VALUE" being two examples. These should not be confused with TOTAL and VALUE -- the string is actually surrounded by double quotes.
What I noticed is that the switch statement below doesn't work because it's looking for TOTAL not "TOTAL":
switch ($statTypeName) {
case "TOTAL":
echo "<br>TOTAL";
break;
case "VALUE":
echo "<br>VALUE";
break;
}
To get this working, I had to put a single quote around the case -- '"TOTAL"'.
In my text editor (Notepad++), it is difficult to see the single quote around the double quotes.
I know this isn't a common issue, but what would be the "professional" way of solving this? The way I did it, or should I be extracting the string from the quoted string and do away with the double quotes altogether..?
Thanks!
case "\"TOTAL\"":
Escape the inner double quotes. It will work the same way and might be a little more visible to the reader
What you're running into is indeed common, and you can go about it a couple different ways. There's nothing wrong with the way you're doing it, or #KyleBanks solution (escaping the double quotes). Given php provides single and double quote string definitions, I prefer the first. But its up to your preference, or your dev team.
As far as extracting the substring within the string quotes.. it depends on what they're there for in the first place.
I would suggest using a better font in Notepad++. I personally use Consolas however here you can find heaps of other good options:
Recommended Fonts for Programming?
Other then changing font escaping quotes as was suggested is another alternative:
case "\"TOTAL\"":
You can also try to strip quotes:
switch (substr($statTypeName, 1, -1)) {...}
but i consider it as a more dangerous approach unless you start using more complicated code to strip them with checks and everything in which case it clearly becomes an overkill.
Except if your given code is not part of some kind of StatType class and is dealing internally with the representation of stat type states my answer might be missing the point a bit, but in any case here it is.
In fact you are doing something wrong here and what you are asking is to find a way to workaround the essential problem you are having. Instead, you should fix the essential problem.
Essential problem is that you are missing one layer of abstraction which will sit between the way you are representing your statType and the way you are using it.
So, your program should not care if you call your statType:
"TOTAL" or '"TOTAL"' or "Total" or "total"
What you need to care is that your statType is in certain state in one moment of program execution. How that representation of the state is implemented ( a string with quotes or a number) is detail of implementation and your switch statement should not care about it.
What happens if you decide to change your statTypeName to be without quotes for example. Than you'll have to go to every line of code that depended on it having quotes and to change it. If you would hide the implementation details in some way you would not need to change more than one line of code.
Maybe one approach to setting abstraction around statTypes? (simplified for clarity)
class StatType
{
const TOTAL = 0;
const VALUE = 1;
// etc.
}
switch ($statType->type()) {
case StatType::TOTAL:
echo "<br>TOTAL";
break;
case StatType::VALUE:
echo "<br>VALUE";
break;
}