Whats the difference between these codes [closed] - php

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.

Related

Brackets in PHP double-quoted strings [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
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.

Mixing html and php variables inside an echo statement

This may be a problem of my trouble with using single and double quotes in one statement. But I have this piece of code:
echo '<form>
<input type="submit" value="$number" onClick="function();">
</form>'
The problem with this is that the submit button says the phrase $number instead of the value of that variable.
So I looked around and found this solution:
echo "<form>
<input type='submit' value='$number' onClick='function();'>
</form>
This outputs the value of $number correctly, but I am used to using single quotes around my echo statements and would like to keep it that way. Why does just switching all single quotes into doubles, and doubles into singles fix the problem? And is there a modification to the first bit of code that would allow me to keep the single quotes on echo, and double quotes on the attributes?
In PHP, double quoted strings are automatically parsed for any variables contained within, but single quoted strings are not. Therefore:
$myVar = 21;
echo "myVar: $myVar"
This outputs the text: myVar: 21
Whereas:
$myVar = 21;
echo 'myVar: $myVar'
This outputs the text: myVar: $myVar
One problem with your code is that in HTML, the values of elements' attributes must be enclosed in double quotes, not single quotes. I know that some browsers will accept this form (or even no quotes at all), but this is not the correct method.
There are various ways of achieving what you wish, correctly.
Method one: Escaping double-quoted strings:
$myVar = 21;
echo "<div id=\"$myVar\"></div>";
While this may be a rather inelegant solution, it will work.
Method two: Using string concatenation with single (or double) quoted strings:
$myVar = 21;
echo '<div id="' . $myVar . '"></div>';
This offers a better solution IMO because you can use function calls or any other PHP code in there if you wish.
WARNING:
Please note that when you aren't certain of the contents of $myVar (i.e. the user enters it in), putting it directly into HTML code is a security vulnerability in the form of cross-site scripting (XSS). Imagine the user enters something like this:
lol"><script>alert('XSS!');</script></div><div id="lol2
This will cause the resulting HTML code to contain the following:
<div id="lol"><script>alert('XSS!');</script></div><div id="lol2"></div>
This is just a benign example, but an attacker could easily use the same technique to steal a user's cookies (to pretend to be logged in as that user). The message here is that when you aren't 100% sure of the contents of a variable, don't insert it into HTML code directly. Instead, call htmlspecialchars($myVar). This would translate to the following:
$myVar = $_POST['whatever'];
echo '<div id="' . htmlspecialchars($myVar) . '"></div>';
In PHP, variables inside double quotes are processed and evaluated, while in single quotes everything is considered as part of the string.
A better explanation here:
http://www.trans4mind.com/personal_development/phpTutorial/quotes.htm
double quote example from the above link:
$something="Oh something";
echo "My answer is $something.<br>";
//result is: My answer is Oh something
single quote example from the above link:
echo 'My answer is $something.<br>';
//result is: My answer is $something.
When you use the single quote, everything inside is taken literally, except single quotes. When using double quotes, anything starting with a dollar sign ($) is assumed to be a variable by PHP. When using variables, I usually like to start the echo with a double quote.
If you want to keep using single quotes, you'll need to use the append operator (a period).
echo '<form>
<input type="submit" value="' . $number . '" onClick="function();">
</form>';
You could just do this and avoid the whole song and dance. I think it is easier to read.
<form>
<input type="submit" value="<?php echo $number; ?>" onClick="myFunction()">
</form>
This outputs same to me
echo '<link rel="apple-touch-icon-precomposed" sizes="57x57" href='. ${base_url_favicon} . '/apple-touch-icon-57x57.png />'."\n";
echo "<link rel='apple-touch-icon-precomposed' sizes='57x57' href='${base_url_favicon}/apple-touch-icon-57x57.png' />\n";
PHP differentiates between single and double quoted strings as being different things. Single quoted strings are literals, you want them output as is. Double quoted strings are to be interpreted (scanned) for any PHP variables and the appropriate replacements made.
This is simply a feature (and a useful one) of the language. I would actually recommend that you get used to using double quotes for strings in all languages. There is no language where it is unacceptable and in staticly typed languages (C, C++, Java, ...) single quotes indicate a character while double quotes indicate a string. That is, String foo = 'my string'; would error in Java as would char * foo = 'my string'; in C or C++. However, char foo = 'a'; is valid, as is String foo = "my string";
Only if you need to eke out the last nanoseconds of performance from PHP might you go through and convert double quoted strings to single quoted strings. In other languages it doesn't matter. Afaik, PHP is the only language that make this string specific double vs. single quotes distinction.
PHP performs what is called variable interpolation on double-quoted strings, which means that the strings are searched for any variables that they might contain, whose values are substituted in the string. If you want to keep the single quotes, you will need to concatenate your strings and variables together like so:
echo '<form>
<input type="submit" value="' . $number . '" onClick="function();">
</form>';
Or, if you want to keep the double quotes, you can escape the double quotes that you want to print:
echo "<form>
<input type=\"submit\" value=\"$number\" onClick=\"function();\">
</form>"

New to programming can't figure out how to format php syntax [closed]

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 10 years ago.
i am trying to have the final output be
$<a style='cursor: pointer; class="photogallery-album-thumbs" onclick=fetchalbum(albumid and albumname)>
here is the code
I know it is completely messed up.
$echo '<a style='cursor: pointer; onClick=fetchAlbum(' . $values['aid'] . "\" class='photo-gallery-album-thumbs-title' " . $values['name'] . ")>";
thank you in advance.
Best thing todo is get a good code editor with syntax highlighting, one built for PHP coding.
But here are some basics:
<?php
/*Standard Variable--
Anything placed between quotes is treated as a string.
A string quote must start and end, you can continue a string but that block
must also have a start and end quote.
*/
$variable_name = "Value";
//or
$variable_name = 'Value';
//If you have a line of html with lots of double quotes, its sometime easyier to use single quotes
$variable_name = '<a style="cursor: pointer; onClick=fetchAlbum("'.$values['aid'].'") class="photo-gallery-album-thumbs-title"'.$values['name'].'")>';
//Or you have to escape the quotes or replace them with single
$variable_name = "<a style=\"cursor: pointer; onClick=fetchAlbum(\"".$values['aid']."\") class=\"photo-gallery-album-thumbs-title\"".$values['name']."\")>";
//You can also use curly brackets on double quotes but you cant use them on single
$variable_name = "<a style=\"cursor: pointer; onClick=fetchAlbum(\"{$values['aid']}\") class=\"photo-gallery-album-thumbs-title\"{$values['name']}\")>";
//Also you cant put carriage returns or tabs ect in single quotes
$variable_name = "\tSome value\r\n";
//tho yo can do
$variable_name = "\t".'Some value'.PHP_EOL;
//Using double quotes for variable assignment or printing is slower then single quotes
//Concatenation
$variable_name = "v"."a"."l"."u"."e";
//variable continuing
$variable_name .= "value";
//simple echoing out
echo 'Some value';
echo "Some value";
echo $variable_name;
print "Some value";
//or you can break out of php and put your html
?>
I think it's better to use double quote variable interpolation, but reference variables with curly brackets {}. So your php is pretty easy to format / read,
ie:
echo "<a style='cursor: pointer;' onClick='fetchAlbum({$values['aid']})' class='photo-gallery-album-thumbs-title' {$values['name']}>";
Curly brackets make it easy to avoid awkward concats (to me).
If the dollar sign is supposed to be in front of this anchor, you need to escape it like:
echo "\$ ... ";
Try this line:
echo '<a style="cursor: pointer;" onClick="fetchAlbum('.$values['aid'].')" class="photo-gallery-album-thumbs-title">'.$values['name'].'</a>';
It's important to have the same count of quotes. They work like brackets like in math.
The dollar sign is not necessary. The $ indicates most likly a variable. A function name must not contain a dolar sign.
From the php documentation:
Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

Difference between uses of inverted commas in PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between single quote and double quote string in php
Can you use " and ' interchangeably, 100%? Or is there a reason or use for each? What is the difference exactly?
Observe for yourself:
$name = 'John';
echo "Hello $name" . '<br>';
echo 'Hello $name';
Result:
Hello John // result from double quotes
Hello $name // result from single quotes
As can be seen variables inside double quotes are parsed while in single quotes they aren't.
So when you put variables inside double quotes, they can be parsed and their correct value is output whereas with single quotes, variables are not parsed and you get the same output of variable name itself as in Hello $name.
Since variables inside single quotes aren't parsed, using them is just a little good when it comes to performance.
If there is no question of variables inside quotes, you can use them inter-changeably though keeping above performance tip in mind.
For more information, you can look at the official documentation.
Just to add to the great answer of Sarfraz, there are certain situations where you would want to use one or the other.
Single quotes ('') are always parsed slightly (minutely) faster than double quotes so if you are an optimization freak, a good rule of thumb is to use single quotes instead of double quotes if you will not be parsing any variables.
However, if you have tons of variables and don't want to do something like:
echo 'My name is ' . $name . '!';
then you're better off with double quotes.
However when dealing with html output, you may consider the hassle of escaping your double quotes too tedious to deal with:
echo "<p id=\"myParagraph\">$name</p>";
So in this case the vote goes to single quotes.
Another thing is that when you build SQL queries with PHP, you may notice that you might prefer using double quotes to be able to parse variables and avoid escaping the single quotes:
"SELECT * FROM CoolGuys WHERE Name = '$name'";
In the end it's all a matter of preferrence. :)
Good luck!

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.

Categories