Whats the proper way to do concatenation in PHP? - php

I understand that there is a difference between single quoted and double quoted strings.
And after reading other stackOverfow questions and looking at this article it seems most people agree that the performance gain of using single quotes is negligible.
As a new PHP user always using double quotes seems the most logic and least confusing way. But why do people still split their double quoted links?
<?php
$a = '12345';
echo "Numbers: $a !"; //What I think is good
echo "Numbers: " . $a . " !"; //What my teacher,book and tutorials use.
echo 'Numbers: ' . $a . ' !'; // Trick that gave a noticeable performance gain pre-PHP 4.3
?>
Why would one prefer the second or third way in the latest version of PHP today?

Well, let's say you have $a = "apple";, and you wanted to put it in the string "I love ______s!"
Using interpolation, your "preferred" method, you might try this: "I love $as!", but of course this won't work.
This is why I prefer using "I love ".$a."s!", as this prevents any kind of confusion. It also makes it very easy to change it to an array access for whatever reason, so it's more "future update-proof". It should also be noted that most code editors can't highlight the interpolated variable, so it's harder to find visually.

I usualy use the third way:
echo 'Numbers: ' . $a . ' !';
I use single quotes as much as possible because I think it looks much cleaner. When I need things like a newline in my string I usually write it seperately from the rest of the string. This also points out this "special" string a bit more:
echo 'Numbers: ' . $a . ' !' . "\n";
Also I think having variables inside double quoted strings ("like $so") is unclear and you won't have syntax highlighting in many editors.

Related

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.

PHP beginning programming, use of quotes

I just started studying PHP and I'm having some difficulty comprehending the use of single and double quotes.
The output I'm trying to get is: She said, "Hello, your IP address is 'localhost'"
Here's the code I have so far, with no erros:
<?php
echo 'She said, "Hello, your IP address is ' . $_SERVER['SERVER_NAME'];
?>
When trying to add the single quotes to the SERVER_NAME and the final double quote, I get errors.
Can you provide me with any further information to understand how to use and add single and double quotes for output?
If you are new to PHP, I recommend you take a look at the documentation for Strings to avoid potential pitfalls in your future projects.
Quotes must be paired, so you need to keep track of where one type of quotes ENDS and another BEGINS.
Example:
John wrote: "She said 'Hello' to me"
Similarly, when you are inserting data within a quoted string:
John wrote: "She said '" .varname. "Hello' to me"
or, in your initial example:
echo 'She said, "Hello, your IP address is ' . $_SERVER['SERVER_NAME'] . '"';
Do you see how we first closed the outside quote, added the external var, then re-opened the outside quote in order to continue the quoted text? In your example, all that was left to add was a 'string' containing the closing quotation mark (also a character): ' " '
A good idea is to use an editor that helps with that. I recommend Notepad++. Not only does it have the syntax highlighting to help you keep track of paired questionmarks, paretheses, brackets, etc, but it also has an incredible FTP tool that immediately FTPs changed files up to your server when you save them.
This way will work:
<?php
echo 'She said, "Hello, your IP address is ' . $_SERVER['SERVER_NAME'] . '"';
?>
You'll need to change to echoing with double quotes in order to use escaping. Then escape the double quotes you want to print with \"
<?php
echo "She said, \"Hello, your IP address is '" . $_SERVER['SERVER_NAME'] . "'\"";
?>
You can also do it this way:
echo "She said, \"Hello, your IP address is {$_SERVER[SERVER_NAME]}\"";
I've escaped the " marks where they are meant literally, and wrapped the array reference in braces. Note that inside a string, associative array lookups don't need quoting, but outside of a string, they do.
In PHP variable can't run in single quotes, it will be treated as a string.
For e.g:
$a = "Hello World";
echo "$a";
Output:
Hello world
echo '$a';
Output:
$a

Question regarding embedding variables in double-quoted strings in PHP

Are the following instructions equivalent?
# 1
$str = "$var1$var2</td>";
# 2
$str = "$var1" . "$var2" . "</td>";
EDIT: Thank you all.
header('Location:Question regarding anonymous methods as class members);
Essentially, but within a string it's recommended to contain the vars in {}:
$str = "{$var1}{$var2}</td>";
This is also useful because it allows you to do things like:
$str = "{$obj1->getName()}{$obj1->getDescription()}</td>";
You end up with the same string but the double quotes around each variable is superfluous. You could eliminate them and have:
$str = $var1 . $var2 . '</td>';
Most syntax highlighters color variables outside of strings different than strings, making it easier to scan.
Yes they are equivalant. When writing strings and putting variables in them, it is always preferable to write whatever is most readable (and actually works) by you or the team you work with. Ignore anyone who talks about time taken to parse single quoted strings Vs double quoted strings, this is micro-optimisation and the Root Of All Evil.

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.

Print newline in PHP in single quotes

I try to use single quotes as much as possible and I've noticed that I can't use \n in single quotes. I know I can just enter a newline literally by pressing return, but that screws up the indentation of my code.
Is there some ASCII character or something that I can type that will produce newline when I'm using single quotes?
No, because single-quotes even inhibit hex code replacement.
echo 'Hello, world!' . "\xA";
echo 'hollow world' . PHP_EOL;
Use the constant PHP_EOL then it is OS independent too.
If you are echoing to a browser, you can use <br/> with your statement:
echo 'Will print a newline<br/>';
echo 'But this wont!';
FYI it is possible to get newlines into strings without double quotes:
printf('Please%1$sgive%1$sme%1$snewlines%1$s', PHP_EOL);
Which may be useful If your irrational fear of double quotes knows no bounds. Though I fear this cure may be worse than the disease.
I wonder why no one added the alternative of using the function chr():
echo 'Hello World!' . chr(10);
or, more efficient if you're going to repeat it a million times:
define('C_NewLine', chr(10));
...
echo 'Hello World!' . C_NewLine;
This avoids the silly-looking notation of concatenating a single- and double-quoted string.
The only escape sequence you can use in single quotes is for the single quote itself.
$foo = 'That\'s great';
The only way you could insert a new line into a string created with single quotes is to insert a literal newline
$bar = 'That\'s
cheating';
There IS a difference on using single VS double quotes in PHP
e.g:
1. echo '$var\n';
2. echo "$var\n";
in 1, PHP will print literally: $var\n
in 2, PHP will have to search the location in memory for $var, and return the value in that location, also, it will have to parse the \n as a new line character and print that result
We're in the range of millionths of a second, but there IS a difference in performance. I would recommend you to use single quotes whenever possible, even knowing you won't be able to perceive this performance increase. But I'm a paranoid developer when it comes to performance.
You may want to consider using <<<
e.g.
<<<VARIABLE
this is some
random text
that I'm typing
here and I will end it with the
same word I started it with
VARIABLE
More info at: http://php.net/manual/en/language.types.string.php
Btw - Some Coding environments don't know how to handle the above syntax.
You can use this:
echo 'Hello World' . "\n";
This worked well for me:
print_r('Hello world'.PHP_EOL);
No, according to documentation, PHP recognize no special symbol in single quotes. And there is no single reason to use single quotes as much as possible
in case you have a variable :
$your_var = 'declare your var';
echo 'i want to show my var here'.$your_var.'<br>';

Categories