PHP beginning programming, use of quotes - php

I just started studying PHP and I'm having some difficulty comprehending the use of single and double quotes.
The output I'm trying to get is: She said, "Hello, your IP address is 'localhost'"
Here's the code I have so far, with no erros:
<?php
echo 'She said, "Hello, your IP address is ' . $_SERVER['SERVER_NAME'];
?>
When trying to add the single quotes to the SERVER_NAME and the final double quote, I get errors.
Can you provide me with any further information to understand how to use and add single and double quotes for output?

If you are new to PHP, I recommend you take a look at the documentation for Strings to avoid potential pitfalls in your future projects.

Quotes must be paired, so you need to keep track of where one type of quotes ENDS and another BEGINS.
Example:
John wrote: "She said 'Hello' to me"
Similarly, when you are inserting data within a quoted string:
John wrote: "She said '" .varname. "Hello' to me"
or, in your initial example:
echo 'She said, "Hello, your IP address is ' . $_SERVER['SERVER_NAME'] . '"';
Do you see how we first closed the outside quote, added the external var, then re-opened the outside quote in order to continue the quoted text? In your example, all that was left to add was a 'string' containing the closing quotation mark (also a character): ' " '
A good idea is to use an editor that helps with that. I recommend Notepad++. Not only does it have the syntax highlighting to help you keep track of paired questionmarks, paretheses, brackets, etc, but it also has an incredible FTP tool that immediately FTPs changed files up to your server when you save them.

This way will work:
<?php
echo 'She said, "Hello, your IP address is ' . $_SERVER['SERVER_NAME'] . '"';
?>

You'll need to change to echoing with double quotes in order to use escaping. Then escape the double quotes you want to print with \"
<?php
echo "She said, \"Hello, your IP address is '" . $_SERVER['SERVER_NAME'] . "'\"";
?>

You can also do it this way:
echo "She said, \"Hello, your IP address is {$_SERVER[SERVER_NAME]}\"";
I've escaped the " marks where they are meant literally, and wrapped the array reference in braces. Note that inside a string, associative array lookups don't need quoting, but outside of a string, they do.

In PHP variable can't run in single quotes, it will be treated as a string.
For e.g:
$a = "Hello World";
echo "$a";
Output:
Hello world
echo '$a';
Output:
$a

Related

PHP variables and strings

Getting very confused with echoing an HTML anchor with a variable inside.
<?php
echo ' Next';
?>
I've tried so many variations of lost which ones I've tried. One of the attempts was with curly brackets { but still nothing. I know I'm getting my single and double quotes muddled up!
Could somebody please put me straight on this one. Also, what is the rules for apostrophes and quotes in PHP. If I want to echo something, what shall I start it with, an apostrophe or a quote.
<?php
echo ' Next';
?>
If you want to do some math of other trickery inside an echo, you will need to surround it in brackets.
Edit: #DaveRandom points out that the exception to the trickery clause is $var++ and ++$var.
If you use ' when printing string, everything inside is treated as a text.
If you use ", variables passed inside are converted to the their values.
However it's impossible to do a math operations inside ". You have to escape it and do it in 'PHP way'.
<?php
echo ' Next';
?>
Use double quotes "something" and surround the variables with curly brackets when they are inside the quotes.
echo " <a href='?p={$current_page+1}'>Next</a>";
You can also use string concatenation, which basically means joining a few strings together:
echo 'something' . 'something else' . $my_variable;
As for escaping, if anywhere inside some quotes you want to insert a quote of the same type (e.g. if you surround your script with double quotes and you want to insert a double quote), you need to escape these quotes by prepending them with a backslash - \.
For example you want to output Text and you have surrounded it in double quotes, you need to escape these double quotes in the HREF attribute by prepending them with a backslash \, so the result should be Text.
The following are valid ways of escaping and displaying characters:
echo "it\" so nice to be here";
echo 'it\'s so nice to be here';
echo "it's so nice to be here"; // Different quotes, no need to escape
echo 'it"s so nice to be here'; // Different quotes, no need to escape
The following will result in an error:
echo 'it's so nice the be here';
Because the PHP interpreter will assume the expression to be ended with the quote found in it's, resulting in the rest of the line being treated is invalid code.
For more information you can read the PHP documentation on the echo() function and this wonderful article on Quotes and Strings as well.
I assume you want to do this:
echo ' Next';
You can try This
$link = ' %s';
printf($link, $current_page - 1, "Prev");
printf($link, $current_page + 1, "Next");

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

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

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/

Using PHP variables inside HTML tags?

I am pretty new to php but I'm stuck on this problem... Say i wait to put a link to another site with a given parameter, how do I do it correclty?
This is what i have now:
<html>
<body>
<?php
$param = "test";
echo "Click Here;
?>
</body>
</html>
Well, for starters, you might not wanna overuse echo, because (as is the problem in your case) you can very easily make mistakes on quotation marks.
This would fix your problem:
echo "Click Here";
but you should really do this
<?php
$param = "test";
?>
Click Here
You can do it a number of ways, depending on the type of quotes you use:
echo "<a href='http://www.whatever.com/$param'>Click here</a>";
echo "<a href='http://www.whatever.com/{$param}'>Click here</a>";
echo 'Click here';
echo "Click here";
Double quotes allow for variables in the middle of the string, where as single quotes are string literals and, as such, interpret everything as a string of characters -- nothing more -- not even \n will be expanded to mean the new line character, it will just be the characters \ and n in sequence.
You need to be careful about your use of whichever type of quoting you decide. You can't use double quotes inside a double quoted string (as in your example) as you'll be ending the string early, which isn't what you want. You can escape the inner double quotes, however, by adding a backslash.
On a separate note, you might need to be careful about XSS attacks when printing unsafe variables (populated by the user) out to the browser.
There's a shorthand-type way to do this that I have been using recently.
This might need to be configured, but it should work in most mainline PHP installations.
If you're storing the link in a PHP variable, you can do it in the following manner based off the OP:
<html>
<body>
<?php
$link = "http://www.google.com";
?>
Click here to go to Google.
</body>
</html>
This will evaluate the variable as a string, in essence shorthand for echo $link;
I recommend using the short ' instead of ". If you do so, you wont longer have to escape the double quote (\").
In that case you would write
echo 'Click Here';
But look onto nicolaas' answer "what you really should do" to learn how to produce cleaner code.
You can embed a variable into a double quoted string like my first example, or you can use concantenation(the period) like in my second example:
echo "Click Here";
echo 'Click Here';
Notice that I escaped the double quotes inside my first example using a backslash.
HI Jasper,
you can do this:
<?
sprintf("Click Here", $param);
?>
Heredoc may be an option, see example 2 here: http://php.net/manual/en/language.types.string.php

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

Categories