Adding line break using PHP



For the formatting purpose we need to add line breaks in our output or strings to store in MySQL tables and all. Here I am describing about various methods to add line break using PHP.

In HTML we can add a line break using <br> or <br /> tag.
For this purpose in PHP we need to simply echo that tag like following code

<?php
echo "syam is here<br>for teaching you PHP";
?>

Its output will be
syam is here
for teaching you PHP
( We can see that a line break is added after “syam is here”)

But in several other cases line break is applying using “n” or “rn”, like data storage in csv , txt files or mysql tables or data in a text area etc. In that cases we need to use function nl2br()
to convert the “n” into “<br>” tags to display line break.

See the sample PHP program for display line break using nl2br()

<?php
echo nl2br("syam is herenfor teaching you PHP");
?>

Its output also will be same as our previous PHP program
syam is here
for teaching you PHP
( we can see that “n” is decoded to <br> tag by nl2br() )

There is PHP_EOL constant available instead of using “n: or “rn”.

See the following sample PHP program with constant PHP_EOL

<?php
echo nl2br("syam is here".PHP_EOL."for teaching you PHP");
?>

Its output also will be same as our previous PHP programs
syam is here
for teaching you PHP
( here we can see that constant PHP_EOL is converted into line break using nl2br )

Most of the time we can use “<br>” tag itself for displaying the line breaks in our HTML contents or displaying areas. The other things will come under some advanced cases that we can understand in our later postings.