Forum Moderators: coopster

Message Too Old, No Replies

print line break with single and double quotes

print line break with single and double quotes

         

drooh

8:55 pm on Jun 20, 2011 (gmt 0)

10+ Year Member



just trying to figure out why this works

echo "hello\n";

but this doesnt

echo 'hello\n';

I prefer to use single quotes, is there any way to get a line break while using single quotes?

drooh

9:13 pm on Jun 20, 2011 (gmt 0)

10+ Year Member



I found that I can do something like this

define("n", PHP_EOL); // creates new line

then

echo 'hello'.n;

Is there a way to tab over? without using \t ? Like PHP_EOL ?

drooh

11:19 pm on Jun 20, 2011 (gmt 0)

10+ Year Member



Found this seems to work

define("n","\n"); // new line
define("t","\t"); // tab

Usage:

$xml = '<?xml version="1.0"?>'.n;
$xml .= t.'<'.$outer_tag.'>'.n;

penders

12:19 am on Jun 21, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You seem to have pretty much figured this out already.

In PHP, double quoted "..." and single quoted '...' strings do behave differently. They are both strings, but double quoted strings support a lot more escape sequences (newline, tab, etc.) and also support variable expansion.

eg. Variable expansion:
$myvar = 'World'; 
echo "Hello $myvar"; // Outputs: Hello World
echo 'Hello '.$myvar; // Outputs: Hello World


In the above example you need to use string concatenation (.) to join the strings together if using single quoted strings. Using double quotes in this respect is easier to read (and code). However, double quoted strings are possibly slower to process. But if you are having to use a lot of string concatenation then there might not be much of a difference.

In your last example which is easier to read? Which is quicker?
$xml .= t.'<'.$outer_tag.'>'.n; 
$xml .= "\t<$outer_tag>\n";


Just to add, the constant PHP_EOL returns the line endings appropriate to the operating system on which PHP is running, so on Linux this will be "\n", but on Windows this will be "\r\n".

I will always use single quoted strings wherever possible, but sometimes it is more appropriate to use double quotes or even heredoc [php.net] syntax.

More information on the PHP manual page about Strings [php.net]

In your example above, you could use single quotes around the first argument:
define('t',"\t"); // tab