I've tried every method to output a newline in PHP. Why doesn't the following work? :
<?php
$foo = 'bar';
echo "Hello \n $foo!";
?>
This should output a newline between hello and bar but it isn't.
I also tried \r\n instead of \n
I've tried every method to output a newline in PHP. Why doesn't the following work? :
<?php
$foo = 'bar';
echo "Hello \n $foo!";
?>
This should output a newline between hello and bar but it isn't.
I also tried \r\n instead of \n
If you using it as command line script this would work. I would use PHP_EOL
for this since it chooses the right line break for the OS.
However if you are working with HTML (viewing the result in browser for example) you have to use the HTML way of linebreaks which is: <br />
To output a new line in HTML you need to use HTML's representation of a new line which is <br/>
php has a function for you that converts all natural new lines to HTML new lines > nl2br()
Then your code should look like
<?php
$foo = 'bar';
echo nl2br("Hello \n $foo!");
?>
Use <br>
when inserting line break in html
To output a new line visually (in a browser), you need HTML
:
echo "Hello\n<br />$foo!";
\n
is a system line feed.
if you view the source you will see it actually DOES have a new line in it, But white space doesnt matter in HTML (what the browser displaying the output is expecting) but adding a <br />
to your statement will produce a new line because this is the way browsers read new lines and display them.
"; – Mark Mar 02 '21 at 02:38