Home » Coding Questions » PHP Questions » How to Create a New Line in PHP | 2 Easy Methods

How to Create a New Line in PHP | 2 Easy Methods

How to Create New line in PHP

By default, when the code executes, the text does not shift on a new line in any programming language. Every programming language provides various methods to add line breaks. Here, We have 2 easy methods to create a new line in PHP.

Method 1: Use <br> tag to add new line in PHP

To insert text on a new line in PHP, you can use the <br> tag inside a text string. Like this below.

In the code example below, we have a string full of text and we used <br> tag to shift text on newline.

<?php
  //use <br> tag inside a string where you want the text to shift on newline in PHP
  echo "The text will show on newline from here, <br> from here, <br> from here, <br> and from here. <br> So, this is how you can create a newline.";
  ?>

In the above code, if you see the text inside the string we used <br> tags 4 times. After every tag, the text shifts to a new line.

Output:

The text will show on newline from here,
from here,
from here,
and from here.
So, this is how you can create a newline.

Wherever you put <br> tag inside a string the text automatically shifts on newline from there.

Method 2: Use nl2br() function

You can use the nl2br() function to insert line break in PHP. With this function, we use PHP newline character \n inside string where we want a line break.

I used the same text. The syntax of using the PHP link break function is below.

<?php
  //use <br> tag inside a string where you want the text to shift on newline in PHP
  echo nl2br("The text will show on newline from here, \n from here, \n from here, \n and from here. \n So, this is how you can create a newline.");
  ?>

If you noticed that in the code we replaced the <br> tag with \n character. The PHP newline character is now showing 4 times in the about code.

The output of this code will be the same as above.

This is how you can use the PHP newline function.

There is one more method to insert a newline in PHP but that sometimes doesn’t work on some systems. So, we do not recommend you to use that.

Hope you understood.

That’s it for now. See more PHP Tutorials.

If you have any questions related to this tutorial. Then feel free and ask that question, in the comments section below.

Share and Subscribe for More.

Leave a Reply

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