How to Echo New Line in PHP

There are several ways to print a new line in PHP. Line break is quite important factor of content formatting and organization. In addition, content management is required for better user experience of the website.

Line break helps to make content more readable with proper usage. There are many ways to enter a new line in PHP.  Here we will discuss all the available methods to print a new in PHP.

New Line in PHP

Using <br> Tag

Whatever we echo or print in PHP, it gives us an output in a browser where “\n” and “\r\n” do not work. Browser requires HTML tags to understand the content formatting.

In HTML <br> is the official tag of line break. We can use <br> tag where we want to print new line in HTML. Even more, we can directly print it in PHP.

Example

<?php
echo "HTML <br>
CSS <br>
JavaScript";
?>

Output

HTML
CSS
JavaScript

Using nl2br() Function

It is easy to just put a <br> tag in PHP string and echo it. But what if there is lots of data available to print?

At that time writing <br> code in lengthy passages would be waste of our valuable time. Here comes an easy way to do that in PHP.

PHP has a default function named as nl2br(), which converts all the line breaks to <br> tag in any PHP string.

Example

<?php 

// Line break notation using \n
$str = "HTML\nCSS\nJavaScript"; 
echo nl2br($str); echo "<br>-----------------------<br>";

// Line break notation using PHP_EOL
$str2 = "HTML".PHP_EOL."CSS".PHP_EOL."JavaScript"; 
echo nl2br($str2); 
echo "<br>-----------------------<br>";

// Line break notation using string break using Enter Key
$str3 = "HTML
CSS
JavaScript"; 
echo nl2br($str3); 

?>

Output

HTML
CSS
Javascript
-----------------------
HTML
CSS
Javascript
-----------------------
HTML
CSS
Javascript

Conclusion

Printing line break helps to beautify our website formatting and provides high readability for users. I hope now you have a complete understanding of the PHP line break and ways to do it.

Enjoy Programming 🙂

Leave a Reply

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