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?
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.
Using new line tags: Newline characters \n or \r\n can be used to create a new line inside the source code.
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.
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'
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>';
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 "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!
\n
must be in double quotes!
echo '<p>' . $unit1 . "</p>\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With