Line breaks are the separators that are used to escape from continuing with the same line. This is for splitting the lengthy line into small, easily readable chunks to be shown line by line. PHP allows adding these line breaks by using escape sequences or predefined constants, as listed below.
Note: These two PHP escape symbols will be effective only within double-quotes. If we have content that is enclosed by single quotes, then, we should specify the line breaks by pressing the enter key as usual. For example,
<?php
$content = 'PHP line breaks
added by escape sequence
working fine';
?>
But, within single quotes, we can only use static data. Rather, if we want to interpolate PHP variables dynamically, then we need to use double-quotes.
The following program shows how to use PHP line feed and PHP_EOL for adding line breaks for the same content displayed within single quotes.
<?php
$content = "PHP line breaks\nadded by escape sequence\nworking fine";
// OR
$content = "PHP line breaks" . PHP_EOL . "added by escape sequence" . PHP_EOL . "working fine";
echo $content;
?>
In the above program, we can note that the \n is used without any PHP dot (.) separator whereas it is required while using PHP_EOL as a line break to recognize that it is PHP predefined constant.
When we execute the above program, we can not see the effect of added line breaks in the browser for each new line. But it could be seen, when we write the content into a file or to the database since these are actual line breaks.
If we want to see the line breaks with browser output as they are in the file or database, then we need to convert these actual PHP line breaks into HTML line breaks which are provided with the standalone <br/> tags. For this conversion, PHP provides an inbuilt function named nl2br(), that is, converting the new line into the break.
This function required an argument for getting input with which it will search for the new line to be replaced with HTML line breaks. For example, the $content variable that holds the data with actual line breaks will be passed to this function as follows.
<?php
$content = "PHP line breaks\nadded by escape sequence\nworking fine";
// OR
$content = "PHP line breaks" . PHP_EOL . "added by escape sequence" . PHP_EOL . "working fine";
$content = nl2br($content);
echo $content;
?>
As shown in the above code, before printing $content to the browser, it is applied as an argument of nl2br() to make the line breaks visible with browser output.