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.
Related
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 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.
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.
Pretty new to PHP, trying to figure out proper syntax for concatecating variables and such into strings.
For example:
A $mydir = "../../uploads/images/'".$id."'/thumb";
B $mydir = "../../uploads/images/".$id."/thumb";
C $mydir = '../../uploads/images/'.$id.'/thumb";
D $mydir = "../../uploads/images/$id/thumb";
Which one is correct?
What about when you end a string with a variable, but have to comma out to define the next element?
mkdir('../../uploads/images/' . $newid , 0777);
What about when the variable is in the middle?
mkdir('../../uploads/images/' . $newid . '/thumb', 0777);
Lastly, can anyone recommend a good resource for PHP reference? W3Schools isn't cutting it...
Strings in PHP can use either double or single quotes. There is a difference between the two, in that using double quotes will cause PHP to interpolate any variables in the string. For instance:
$var = 'test';
echo "This is a $var"; // outputs: This is a test
echo 'This is a $var'; // outputs: This is a $var
Because of this, using double quotes around your strings is a bit slower, since the string must be interpolated by PHP before it can be output. There is also nowdoc and heredoc support for strings in PHP, as well.
Aside from that distinction there is no difference and you can use them interchangeably, as in the following example:
echo 'I like ' . "concatenating" . ' strings';
It is probably a good idea, though, to be consistent throughout your code. For more information, please refer to the manual
Go to the PHP Manual: http://php.net/manual/en/language.types.string.php
As for the different types of strings:
If you use the double-quoted strings, you can include variables inside of the string like this:
$name = "world";
print("Hello $name");
Single Quotes will not expand variables.
The period is just the concatenation operator. So if you end by concatenating a variable that's fine. I.e. this is ok:
$name = "world";
$greeting = "Hello ".$name;
You shouldn't use your A or B, if you have double quotes, using D is much nicer to read. That is not to say you can't use it, if you like having a hard time reading your strings, go ahead!
The comma after the string doesn't matter
mkdir('../../uploads/images/' . $newid , 0777); // works
mkdir('../../uploads/images/' . $newid . '/thumb', 0777); // works too
mkdir("../../uploads/images/$newid" , 0777); // works and is nicer to read
mkdir("../../uploads/images/$newid/thumb", 0777); // also nicer to read
If the value you want in the string is not a variable, you either have to create a variable, or you have to use regular string concatenation (instead of interpolation)
B and D are correct. The only difference between single and double quotes in PHP is that the content between double quotes is parsed for PHP. From php.net,
When a string is specified in double quotes or with heredoc,
variables are parsed within it.
A - has a pair of unnecessary single quotes.
B - FINE
C - has an incorrect ending quote. should end in a single quote.
D - FINE
for concatenation B or C will both work, however for relative file paths it's usually best to use the
$_SERVER['DOCUMENT_ROOT']
syntax, and access your files relative to your server's html root folder, meaning your syntax will look something like
$_SERVER['DOCUMENT_ROOT']."/folder/foler/".$id."/thumb";
A won't do it.
B is the best.
C has a syntax mistake. Moreover, for strings you generally use ", but on the other hand, ' is used when formatting html like: 'Google!' so you don't need to escape quotes and the code looks nice.
D works, but not recommended. For example in D `"blah $this -> name blah" won't work. That is the reason.
from your choice list, 'B' is fine, so is 'D'. My favorite reference is the official manual: http://www.php.net/manual/en/
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>';