Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

\n or \n in php echo not print [duplicate]

Tags:

string

php

Possible Duplicate:
Print newline in PHP in single quotes
Difference between single quote and double quote string in php

$unit1 = 'paragrahp1';
$unit2 = 'paragrahp2';
echo '<p>' . $unit1 . '</p>\n';
echo '<p>' . $unit2 . '</p>';

This is displaying (on view source):

<p>paragraph1</p>\n<p>paragraph2</p>

but isnt what I’m expecting, not printing the new line, what can be?

like image 690
Albi Hoti Avatar asked Dec 06 '12 10:12

Albi Hoti


People also ask

Does \n work in PHP?

You can use the PHP newline characters \n or \r\n to create a new line inside the source code. However, if you want the line breaks to be visible in the browser too, you can use the PHP nl2br() function which inserts HTML line breaks before all newlines in a string.

What is the \n in PHP?

Using new line tags: Newline characters \n or \r\n can be used to create a new line inside the source code.

How echo () is differ than print () in PHP?

echo and print are more or less the same. They are both used to output data to the screen. The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument.


5 Answers

PHP only interprets escaped characters (with the exception of the escaped backslash \\ and the escaped single quote \') when in double quotes (")

This works (results in a newline):

"\n"

This does not result in a newline:

'\n'
like image 82
Tom van der Woerdt Avatar answered Nov 02 '22 04:11

Tom van der Woerdt


Better use PHP_EOL ("End Of Line") instead. It's cross-platform.

E.g.:

$unit1 = 'paragrahp1';
$unit2 = 'paragrahp2';
echo '<p>' . $unit1 . '</p>' . PHP_EOL;
echo '<p>' . $unit2 . '</p>';
like image 26
Kafoso Avatar answered Nov 02 '22 03:11

Kafoso


Escape sequences (and variables too) work inside double quoted and heredoc strings. So change your code to:

echo '<p>' . $unit1 . "</p>\n";

PS: One clarification, single quotes strings do accept two escape sequences:

  • \' when you want to use single quote inside single quoted strings
  • \\ when you want to use backslash literally
like image 40
Salman A Avatar answered Nov 02 '22 02:11

Salman A


\n must be in double quotes!

echo "hello\nworld";

Output

hello
world

A nice way around this is to use PHP as a more of a templating language

<p>
    Hello <span><?php echo $world ?></span>
</p>

Output

<p>
    Hello <span>Planet Earth</span>
</p>

Notice, all newlines are kept in tact!

like image 20
maček Avatar answered Nov 02 '22 04:11

maček


\n must be in double quotes!

 echo '<p>' . $unit1 . "</p>\n";
like image 34
NullPoiиteя Avatar answered Nov 02 '22 02:11

NullPoiиteя