How To Echo New Line In Php

In PHP, it’s a common scenario where we want to output multiple lines of text, whether it’s for formatting purposes or to improve the readability of the output. In this blog post, we will discuss how to create new lines in PHP using different methods.

1. Using the newline character (\n) or carriage return and newline character (\r\n)

The most straightforward way to create a new line in PHP is to use the newline character (\n) or the combination of a carriage return and newline character (\r\n). The newline character is used for Unix systems while the combination of carriage return and newline character is used for Windows systems. However, keep in mind that this method will only work when outputting to a text file or a console, not when displaying HTML content in a browser.

Example:

    <h2>2. Using the HTML break tag (&lt;br&gt;)</h2>

    <p>When working with HTML content, you can create a new line using the HTML break tag (<strong>&lt;br&gt;</strong>). The browser will interpret this tag and display the content in separate lines accordingly.</p>

    <h3>Example:</h3>
    [sourcecode language="php"]
    <br>";
    ?&gt;
    

3. Using the PHP_EOL constant

Another way to create a new line in PHP is to use the PHP_EOL (End Of Line) constant. This constant automatically detects the appropriate newline character for the current operating system, making your code more portable across different systems.

Example:

4. Using double-quoted strings with the newline character

In PHP, you can use double-quoted strings to include the newline character directly in the string itself. This method also works only when outputting to a text file or a console, not when displaying HTML content in a browser.

Example:

Conclusion

In this blog post, we discussed different methods to create new lines in PHP output. Depending on your use case and where you’re displaying the output, you can choose the method that best suits your needs. Remember to use the HTML break tag for displaying new lines in a browser and the other methods for outputting to a text file or a console.