PHP Line Breaks

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

  1. Linefeed (\n): This is one of the PHP escape sequence to add actual line break in between content.
  2. PHP_EOL: This Predefined constant is used as an representation of end of 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, with in single quotes we can only use static data. Rather, if we we want to interpolate PHP variable dynamically, then we need to use double quotes.

The following program shows about 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";
//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 where as it is required, while using PHP_EOL as a line break to recognize that it is PHP predefined constant.

php_line_break

Purpose of PHP function nl2br()

When we execute the above program, we can not see the effect of added line breaks in 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 stand alone <br/> tags. For this conversion, PHP provides in built function named as nl2br(), that is, converting new line into break.

This function required an argument for getting input with which it will search for 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";
//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.

This PHP code tutorial was published on June 25, 2013.

↑ Back to Top