\n problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
global_erp_solution
Forum Commoner
Posts: 25
Joined: Sun Jul 08, 2012 6:47 am

\n problem

Post by global_erp_solution »

AFAIK, \n is global convention for newline. but

Code: Select all

echo 'a\nb';
produces a\nb
and

Code: Select all

echo "a\nb";
produces ab

Can anybody explain this behavior? and how can one print newline character? I've always used <br>. thanks
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: \n problem

Post by Celauran »

If you look at the HTML source, you'll see a new line between a and b. As you mentioned, though, HTML for newline is

Code: Select all

<br />
.
User avatar
Grizzzzzzzzzz
Forum Contributor
Posts: 125
Joined: Wed Sep 02, 2009 8:51 am

Re: \n problem

Post by Grizzzzzzzzzz »

global_erp_solution wrote:AFAIK, \n is global convention for newline. but

Code: Select all

echo 'a\nb';
produces a\nb
and

Code: Select all

echo "a\nb";
produces ab

Can anybody explain this behavior? and how can one print newline character? I've always used <br>. thanks
single quotation marks indicate to PHP that you want it to treat the string literally, variables and escape sequences will not be parsed and the string is simply outputted as it is (the exception being when using backslashes to escape)

strings in double quotation marks are parsed for variables and the like, and so sequences such as \n or &nbsp; are interpreted.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: \n problem

Post by requinix »

Grizzzzzzzzzz wrote:single quotation marks indicate to PHP that you want it to treat the string literally, variables and escape sequences will not be parsed and the string is simply outputted as it is (the exception being when using backslashes to escape)
Backslashes stay with only two exceptions: \' and \\.

Code: Select all

echo '\a\p\o\s\t\r\o\p\h\e\:\ \'\,\ \b\a\c\k\s\l\a\s\h\:\ \\';

Code: Select all

\a\p\o\s\t\r\o\p\h\e\:\ '\,\ \b\a\c\k\s\l\a\s\h\:\ \
Grizzzzzzzzzz wrote:strings in double quotation marks are parsed for variables and the like, and so sequences such as \n or &nbsp; are interpreted.
PHP does not interpret HTML entities.
User avatar
Grizzzzzzzzzz
Forum Contributor
Posts: 125
Joined: Wed Sep 02, 2009 8:51 am

Re: \n problem

Post by Grizzzzzzzzzz »

requinix wrote:
Grizzzzzzzzzz wrote:strings in double quotation marks are parsed for variables and the like, and so sequences such as \n or &nbsp; are interpreted.
PHP does not interpret HTML entities.
oops :oops: my derp
Post Reply