How to Create New Line in PHP

There are a couple of different ways we can approach creating new lines in PHP, which we will learn in this tutorial.

 

Insert Newline Characters with '\n' or '\r\n'

To create new lines in your source code in PHP, use '\n' or '\r\n' in the string like this:

 

$text = "This one line,\r\n and this is another line.";

echo $text;
This one line, and this is another line.

 

Note - '\n' will only work on Unix-like systems and not Windows systems, while '\r\n' will work on both. It is therefore not recommended to use '\n'.

 

This is a good approach for storing text in an efficient way in a database, however, browsers will not display the new lines as the output in the above example demonstrates.

 

Replace New Lines with br Tags

New lines will not be visible in the browser so they will need to be converted to the HTML equivalent, which is the br tag. Fortunately PHP provides a built-in utility, nl2br() for this task.

 

$text = "This one line,\r\n and this is another line.";

echo nl2br($text);
This one line,
and this is another line.

 

Concatenating br tags

If you are iterating through an array of elements and would like to create a list separated by newlines concatenate a br tag to the end of each string before echoing it.

 

$fruit = ['strawberry', 'orange', 'apple'];

if (is_array($fruit)) {

  $count = 1;

  foreach ($fruit as $f) {
    echo $count .'. '. $f .'<br>';
    $count++;
  }
}
1. strawberry
2. orange
3. apple

 

Newline character for SMS in PHP

To make new lines appear in SMS messages ensure the string is wrapped in " (double quotes) and not ' (single quotes).

 

$text = "This one line,\r\n and this is another line.";

 

Conclusion

You now know how to create new lines in PHP and prepare those strings for display in a browser.

line break new line