M. Blork
M. Blork

Reputation: 29

PHP difference between echo 'string'.'\n'; and echo 'string'."\n";

Given the following statements:

echo 'string1'."\n";
echo 'string2';

The following gets rendered as output:

string1
string2

With these statements

echo 'string1'.'\n';
echo 'string2';

This gets rendered (note the verbatim backslash n):

string1\nstring2

When \n is in double quotes, it makes a new line as it should. when \n is in single quotes, it will be shown in the browser as text.

Can anyone explain this behavior?

Upvotes: 2

Views: 127

Answers (2)

pguetschow
pguetschow

Reputation: 5337

Using single quotes will mark it as a string, so PHP will literally output \n.

See here: PHP Manual


Alternatively use chr() with the ASCII code of a new line as an argument:

echo 'string'.chr(10); 

Or use the <br/> Tag

echo 'string<br/>';

Upvotes: 2

nospor
nospor

Reputation: 4220

http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters

Upvotes: 0

Related Questions