8

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?

Salman A
  • 262,204
  • 82
  • 430
  • 521
Albi Hoti
  • 331
  • 2
  • 4
  • 11
  • 1
    @LightnessRacesinOrbit In the OP's defense, if they're asking such an elementary question, I wouldn't make the assumption they know about PHP's interpolation. – maček Dec 06 '12 at 10:33
  • 1
    and [Difference between single quote and double quote string in php](http://stackoverflow.com/questions/3446216/difference-between-single-quote-and-double-quote-string-in-php) – mario Dec 06 '12 at 10:36

6 Answers6

50

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'
Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
13

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>';
Kafoso
  • 534
  • 3
  • 20
7

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
Salman A
  • 262,204
  • 82
  • 430
  • 521
3

\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!

maček
  • 76,434
  • 37
  • 167
  • 198
2

\n must be in double quotes!

 echo '<p>' . $unit1 . "</p>\n";
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
0
$unit1 = "paragrahp1";             
$unit2 = "paragrahp2";  
echo '<p>'.$unit1.'</p>';  
echo '<p>'.$unit2.'</p>';

Use Tag <p> always when starting with a new line so you don't need to use /n type syntax.

José Pinto
  • 686
  • 6
  • 11
vaibhav
  • 129
  • 4