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.
Related
I tried to do redirect with this syntax:
header("location: readMore.php?id=$post['post_id']");
But it didn't work. It worked only after someone suggested to put curly brackets around $post['post_id']!
The correct syntax is:
header("location: readMore.php?id={$post['post_id']}");
What does the curly brackets do in this case?
Quoting the manual:
When a string is specified in double quotes or with heredoc, variables are parsed within it.
There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.
The complex syntax can be recognised by the curly braces surrounding the expression.
Your first code uses simple syntax, and your second code uses a complex one.
The manual does not explicitly state this, but whitespace in simple syntax seems to be an error, rendering your first code invalid. Complex syntax appears to support the same syntax as regular PHP does as far as I can see, but again this does not seem to be actually guaranteed anywhere.
String interpolation is quite flunky in general:
$a = [['derp']];
$b = $a[0];
// Works. It prints derp
echo "$b[0]";
// Doesn't work. It throws an error
echo "$b[ 0 ]";
// Works. It prints derp
echo "{$b[ 0 ]}";
// Doesn't work. It prints Array[0]
echo "$a[0][0]";
// Works. It prints derp
echo "{$a[0][0]}";
// Doesn't work. It prints { Array[0] }
echo "{ $a[0][0] }";
You get similar issues with $object -> foo and $object->foo->bar.
To me, that is pure madness. For that reason I've come to avoid double quoted strings whenever possible (the only thing I used them for are for escape sequences like "\n"). I instead use single quotes and string concatenation, like so:
header( 'location: readMore.php?id=' . $post[ 'post_id' ] );
This lets you use actual PHP syntax for variables without the horrible death trap that is string interpolation.
I came to this question to know more about constant interpolation syntax when those PHP "<<<" things are used to create multiline strings called Heredocs (which allow variable interpolation, unlike Nowdocs).
However, it seems there is no specific syntax for them, and therefore a simple workaround is to create a closure to do so. In here it is just an anonymous function assigned to a variable that will be invoked with parameters:
$int = 'intruder'; // Variable
define('con', '"smart"'); // Constant
// For complex interpolation:
// 1. Define a closure (anonymous function)
// 2. Assign it to a variable with a short name (e.g.: _ )
// 3. Invoke the function by calling the variable with parameters enclosed in ()
$_ = function ($val){return $val;};
$doc = <<<TXT
Hi there,
One day I caught this $int nearby.
I was then told that actually other {$_(con)} $int was there before.
So who came first, the chicken or the egg?
TXT; // Heredoc
echo $doc;
Output:
Hi there,
One day I caught this intruder nearby.
I was then told that actually other "smart" intruder was there before.
So who came first, the chicken or the egg?
You can test the above online on 3v4l. This was based on this answer with a few more examples with operations inside the interpolation brackets.
When you use double or single quotes, PHP will treat whatever is in it as a string unless you tell it that it’s a variable. PHP understands anything after { followed by $ as a variable and treats it as such. Here is an example:
$Text = "XYz";
echo "name-{$Text}";
The other alternative method is to use concatenation. Here is an example:
header("location: readMore.php?id=" . $post['post_id']);
Brackets allow PHP to read what's inside as a variable. You can do that this way too:
header("location: readMore.php?id=" . $post['post_id']);
PHP's simple string interpolation doesn't recognize quoted array keys, which your example demonstrates perfectly. In fact, the correct way to write this is exactly opposite depending on which syntax used: simple vs complex.
Simple syntax - Wrong
Quoted keys cannot be parsed.
header("location: readMore.php?id=$post['post_id']");
Simple syntax - Right
The unquoted string is the associative array key.
header("location: readMore.php?id=$post[post_id]");
Complex syntax - Wrong
It will work, but only if post_id is a defined constant. If not, you'll get a PHP warning.
header("location: readMore.php?id={$post[post_id]}");
Complex syntax - Right
Written just like outside the string.
header("location: readMore.php?id={$post['post_id']}");
To quote the manual on the complex syntax:
// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";
I'd recommend using complex (curly brace) syntax if using quoted keys. And you really should be using them, because outside the string interpolation unquoted keys are actually constants. It's too bad the simple syntax won't allow them, because it makes code reviews and updating old PHP code more difficult.
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
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.
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>';
Is there any difference between typing:
<?php echo $_SERVER[REQUEST_URI] ?>
or
<?php echo $_SERVER['REQUEST_URI'] ?>
or
<?php echo $_SERVER["REQUEST_URI"] ?>
?
They all work... I use the first one.
Maybe one is faster than the other?
Without quotes PHP interprets the REQUEST_URI as a constant but corrects your typo error if there is no such constant and interprets it as string.
When error_reporting includes E_NOTICE, you would probably get an error such as:
Notice: Use of undefined constant REQUEST_URI - assumed 'REQUEST_URI' in <file path> on line <line number>
But if there is a constant with this name, PHP will use the constant’s value instead. (See also Array do's and don'ts)
So always use quotes when you mean a string. Otherwise it can have unwanted side effects.
And for the difference of single and double quoted strings, see the PHP manual about strings.
The first one is wrong - you're actually looking for a constant REQUEST_URI that doesn't exist. This will generate a notice-level warning.
There's no difference between the other two.
There is a difference between single and double quotes in PHP string handling. A string enclosed in double quotes will be evaluated for embedded variables and escape characters (e.g. \n); a string enclosed in single quotes won't (or not as much).
So, for example,
$hello = "world";
echo "Hello $hello!\n";
echo 'Hello $hello!\n';
echo 'Done';
will output
Hello world!Hello $hello!\nDone
In situations where you have no escape characters or embedded variables, it is slightly more efficient to use single quotes as it requires less processing of the string by the runtime. However, many people (me included) prefer to use double quotes for all strings to save confusion.
As a caveat to Gumbo's answer the third representation - double quotes - actually makes PHP look for variables inside that string. Thus that method might be a little slower (although in a string of 11 characters it'll be negligible - it's better practice not to make PHP do that however).
When PHP comes across plain strings being used as array keys it checks if there is a constant with that name and if there isn't it defaults it back to an array key. Therefore, not using quote marks causes a slight performance hit and there is a possibility that the result will not be what you expect.
$_SERVER[REQUEST_URI]
is syntatically incorrect and AFAIK will not run on a default installation of PHP5. The array index is a string so it needs to be passed on strings. I know PHP4 converted undefined constants to strings inside the square brackets but it's still not good practice.
EDIT: Well unless you define a constant called REQUEST_URI, which you haven't in your example script.
$_SERVER['REQUEST_URI']
is the standard method and what you should be using.
$_SERVER["REQUEST_URI"]
also works and while not wrong is slightly more work for the PHP interpreter so unless you need to parse it for variables should not be used. (and if you need to do so, you need to rethink that part of your program.