Signup/Sign In

How to create a new line in PHP

Answer: Using nl2br() function

The nl2br() function is an in-built PHP function that is used to insert the HTML line break "<br>" at the place of the \n present in the given input string. In most programming languages, we use \n for a line break and to shift the content into the new line. When we use the newline character in PHP, being a markup language, HTML does not understand the concept of character sequence, So whenever we use \n to break the line, it will not break the line. To make this sequence character work, PHP introduced the nl2br() function.

The nl2br() function enables us to use the new line characters \n or \n\r within the PHP. The line break created using this function can be visible in the browser too.

Example: Using sequence characters without nl2br() function

In the given example, we have used the sequence character (\n) within the string without the nl2br() function.

<!DOCTYPE html>
<html>
<head>
	<title>Line break in PHP</title>
</head>
<body>
	<?php
	echo "Welcome to \r\n Studytonight";
	?>
</body>
</html>

Output

As we can see in the output image, the line break is not visible on the browser but it is already done in the code. This is because we did not use the nl2br() function.

howto

Example: Using sequence character (\n) with nl2br() function

In the given example, we have used the nl2br() function to break the line which can be also visible on the browser.

<!DOCTYPE html>
<html>
<head>
	<title>Line break in PHP</title>
</head>
<body>
	<?php
	echo nl2br("Welcome to \n Studytonight");
	?>
</body>
</html>

Output

In the given output, the text "Studytonight" shifted to the next line. This is because of the nl2br() function.

php

Conclusion

In the lesson, we have learned how to create a new line in PHP. The new line in PHP can be created using the nl2br() function, which can be used to insert the HTML line breaks before all newlines in the string.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.