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

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?

This question is related to php string

The answer is


$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.


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


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

\n must be in double quotes!

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

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>';