PhpStorm function that change double quotes to single quotes in string - php

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

Related

Put a variable in a string PHP

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

PHP string concat without the "dot" operator

I'm working to integrate a plug-in into a PHP web application, and one line of the code puzzles me:
$sql = "update inventory set qtyleft='$qtyleft',price='$price',sales=sales+'$sales',qtysold=qtysold+'$qtysold' where id='$id'";
mysql_query($sql);
where $qtyleft, $price, $sales, $qtysold and $id are all variables.
I'm not very familiar with PHP, but I always thought string concatenation in PHP is done by using the . operator and it seems to me that the code above is just a long string without actually putting those variables to the SQL query. Is that the case?
In PHP, double quote (") delimited strings will evaluate variables in them.
$foo = 42;
echo "The answer for everything is $foo"; // The answer for everything is 42
This specific example is very bad because you shouldn't include variables directly in an SQL query, and shouldn't use mysql_query in new code.
See more:
Why shouldn't I use mysql_* functions in PHP?
How can I prevent SQL injection in PHP?
See Variable Parsing section of the Strings manual page.
When a string is specified in double quotes or with heredoc, variables are parsed within it.
If you use single quotes for a string, the variables will not be interpolated. If you use double quotes, they will be.
The code you mentioned will work in PHP without any issues. Please refer PHP Manual for more details.
Other issue that you might need to look forward is the function mysql_query is depreciate. Please refer here. Which gives me a feeling that the plugin you are going to is use not maintained correctly. And one more problem is, its not a good practice to pass the variable directly in the SQL query do to possible security issues
Some call it "variable interpolation". It is explained on the Variable parsing section of the manual page about strings. It helps to read the entire page and also the user comments.
The basic idea is that for strings enclosed in quotes (") and on heredoc blocks, PHP searches for variables inside the string when it needs to use it and replaces them with their values at the moment of the execution. This means the same string can render to different values in different moments of the script's execution.
This is just syntactic sugar, it doesn't change the way the code behaves and any string that contains variables inside can be rewritten using the string concatenation operator (.). Usually this syntax produces shorter source code. Sometimes the code is easier to read this way, other times it is harder because the complex expressions (array access, f.e.) need to be enclosed in curly braces ({ and }) inside the string.

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 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