Proper use of double & single quotes, concatecating periods, and commas - php

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/

Related

Using PHP variable in system() function

I am currently using this command:
system('"C:/xampp/htdocs/csv/txtfiles/PSPPfile.txt"');
I want to having something like with having variable inside, for instance:
$file='txtfiles/PSPPfile.txt';
system('"C:/xampp/htdocs/csv/$file"');
Something like above, kindly help me out. Thanks!
Single quoted strings will display things almost completely "as is." Variables and most escape sequences will not be interpreted.
In other words, youre assigning the argument to system to read $file as is, not as what the variable contains.
Use double quotes to assert that variable gets replaced - or perform string concatenation :
system( 'c:/xampp/htdocs/csv/' . $file );
$file = 'txtfiles/PSPPfile.txt';
system('C:/xampp/htdocs/csv/' . $file);

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.

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.

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

Why does this query have .?

I want to know why the following query have . and "" in ".$_POST['date']." etc.
$query = "INSERT INTO eventcal ('eventDate','eventTitle','eventContent','user',
'user_id') VALUES('".$_POST['date']."','".addslashes($_POST['eventTitle'])."',
'".addslashes($_POST['eventContent'])."')";
If I change to the following, will it make any differences?
VALUES('$_POST['date']','addslashes($_POST['eventTitle'])',
'addslashes($_POST['eventContent'])')
Thanks in advance.
It is the PHP form of concatenation (The quotes mark the end of the strings). In JavaScript and many other languages it is the + character that concatenates.
echo "hello" . " " . "world!"; // Outputs 'hello world'
Yes, making that change would drastically change its meaning.
Finally, this is open to a severe SQL injection attack because date is not properly escaped.
Always sanitize your input and use parameterized queries where possible.
The "dot" operator is PHP's operator for string concatenation. I think that using the addslashes function is a better idea than what you have in the first example but you will still need to use string concatenation as PHP's string interpolation only supports variables.
Single quotes inhibit variable interpolation, and as well the single quotes used in the array index would terminate the string.
Also, use a library that supports query parametrization instead of adding the values in like this.
Yes, only variables are parsed in double quotes which means your functions won't be executed in the second code block.

Categories