How to Echo New Line in PHP

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

Echo New Line in PHP

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 Using <br> Tag

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

In HTML <br> is the official tag of a line break. We can use the <br> tag where we want to print a 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

New Line Using nl2br() Function

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

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

PHP has a default function named 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

Read Also: Find Array Length in PHP

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 *