Open In App

How to create a New Line in PHP?

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

When working with text output in PHP, like creating a webpage, sending an email, or saving to a file, it's important to know how to add a new line. Adding a new line helps break up the text, makes it easier to read, and keeps it looking right whether it's shown in a browser, a terminal, or a file.

How to create a New Line in PHP?

Below are the following ways by which we can create a new line in PHP.

1. Using Line Breaks as in HTML

The <br> tag in HTML is used to give a single-line break. It is self-closing and doesn't require an end tag.

Syntax:

<br>

Example: 

PHP
<?php
echo "Hello, World!<br/>";
echo "This is a new line.<br>";
?>

Output
Hello, World! .<br/>This is a new line.<br>

2. Using new line Tags(\n or \r\n)

Newline characters like \n (for UNIX/Linux) or \r\n (for Windows) are used to create new lines in text-based output, such as in CLI or text files.

Syntax: 

 "\n"

Example 1: 

PHP
<?php
echo "Hello, World!\n";
echo "This is a new line.\n";
?>

Output
Hello, World!
This is a new line.

Syntax: 

"\r\n"

Example 2: 

PHP
<?php
echo "Hello, World!\r\n";
echo "This is a new line.\r\n";
?>

Output
Hello, World!
This is a new line.

3. Using nl2br() Function in PHP

The nl2br() function is used in PHP to convert newline characters (\n) into HTML <br> tags, which helps preserve formatting when displaying text on a webpage.

Syntax:

nl2br(string $string, bool $is_xhtml = true): string

Example:

PHP
<?php
$text = "Hello, World!\nThis is a new line.";
echo nl2br($text);
?>

Output
Hello, World!<br />
This is a new line.

Best Practices

  • Use <br> for HTML: Always use <br> for line breaks in HTML content.
  • Avoid \n in HTML: Don’t use \n in HTML output; it won’t create visible line breaks.
  • Use nl2br() for Text with Newlines: Use nl2br() to convert newlines (\n) into HTML <br> tags when displaying text on web pages.
  • Understand Browser Behavior: Browsers ignore extra spaces and newlines in HTML. Always use <br> for visible line breaks.

Conclusion

In PHP, creating new lines is essential for organizing and formatting text output. Depending on your environment (web, command-line, or file-based output), you can use different methods to insert line breaks.


How to create a New Line in PHP ?

Similar Reads