How to Add a PHP Line Break/New Line Correctly in a String?

Problem:

You want to add a line break in a specific point in a string and print it.

Solution:

In the following you’ll see two ways to add/echo a line break or new line in a string.

Method 1: Using escaping sequence \n

Two steps to add a line break using \n

  1. Add the escape sequence \n at the point you want to add a new line break, then
  2. Use nl2br() function to let PHP interpreter to interprete \n to html <br />

See the following example-

<?php
$str = "Two of the most popular server-side languages are \nPHP and MySQL";
echo nl2br($str);
?>

Output:
Two of the most popular server-side languages are
PHP and MySQL

The escape sequence\n doesn’t work in single quoted string, only works in double quoted and heredoc strings. Inside the single quoted string \n doesn’t have a meaning.

Method 2: Using predefined constant PHP_EOL

One of the core PHP constants is PHP_EOL which define end of a line. See the following example-

<?php
$str = "Two of the most popular server-side langugaes are ".PHP_EOL."PHP and MySQL";
echo nl2br($str);
?>

Output:
Two of the most popular server-side languages are
PHP and MySQL

You can also use <br /> directly in the PHP string to add a line break. It is not the PHP way to do it, but HTML method.As you know, PHP interpreter converts PHP syntaxes to HTML, then, displays it in the browsers. In the similar way, PHP interpreter converts \n and PHP_EOL to <br /> and add line breaks.