PHP Line Breaks

by Vincy. Last modified on June 2nd, 2021.

Line breaks are the separators which are used to escape from continuing with the same line. This is for splitting the lengthy line into small, easy readable chunks to be shown line by line. PHP allow adding these line breaks by using escape sequences or predefined constants, as listed below.

  1. Linefeed (\n): This is one of the PHP escape sequences to add an actual line break in between content.
  2. PHP_EOL: This Predefined constant is used as a representation of the end of the line.

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,

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

$content = "PHP line breaks\nadded by escape sequence\nworking fine";
$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.

Purpose of PHP function nl2br()

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 file or database, then we need to convert this actual PHP line breaks into HTML line breaks which are provided with the standalone <br/> tags. For this conversion, PHP provides inbuilt function named as 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.

$content = "PHP line breaks\nadded by escape sequence\nworking fine";
$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.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this Article