Please tell me what I am doing wrong, when the php file executes is saves the actual folder as "$name" instead of Peter. What am I doing wrong?
Here is my code:
$name = "Peter";
copy_directory('you/','dir/$name');
You'll need to use double quotes in order for the variable to be interpreted as Peter
copy_directory('you/',"dir/$name");
You need to use double quotes if you want to expand variables within a string.
$name = "Peter";
copy_directory('you/',"dir/$name");
Or, alternately, concatenate the variable onto the string:
copy_directory('you/','dir/' . $name);
Use double quotes instead of single quotes;
$name = "Peter"; copy_directory('you/',"dir/$name");
Or alternatively, concatenate the variable;
$name = "Peter"; copy_directory('you/','dir/' . $name);
It's good practice to use concatenation operator while using php variables.
copy_directory('you/','dir/'.$name);
Updated Answer:
This could be big debate what to use. It's everyone's own opinion. But people say we should avoid complexity of double quotes. Double quotes have memory save issues. It doesn't matter for small values.
So I thought it's good practice to use concatenation operator while using php variables.
link1
link2
link3
link4
link5
link6
Problem is that you use the ' but should use there "" or 'dir/'. $name:
copy_directory('you/','dir/$name');
Related
eval("\$data = $myvar('https://www.example.com/json/id='". $_GET['name'] ."'))';
This got me an error, how to concatenate it properly?
Eval is dangerous, but for your specific question above, the quotes were off at the end, and myvar is supposed to be a function. See below:
eval('$data = myvar("https://www.example.com/json/id='. $_GET['name'] .'");');
If you use double quotes like "$data" then $data will first be evaluated and the result or value will be eval'd instead. This is one of the risks of using eval(). If you use double quotes, then escape the $ signs like so:
eval("\$data = myvar('https://www.example.com/json/id=". $_GET['name'] ."');");
Demo: IDEOne
eval("\$data = $myvar('https://www.example.com/json/id=". $_GET['name']."');");
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/
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!
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.
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.