Question

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?

Was it helpful?

Solution 4

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'] . "'\"";
?>

OTHER TIPS

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 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top