Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Echo Line Breaks

What's the difference between \n and \r (I know it has something to do with OS), and what's the best way to echo a line break that will work cross platform?

EDIT: In response to Jarod, I'll be using ths to echo a line break in a .txt log file, though I'm sure I'll be using it in the future for things such as echoing HTML makup onto a page.

like image 767
PHLAK Avatar asked Nov 01 '08 04:11

PHLAK


People also ask

How do you add a line break in PHP?

Answer: Use the Newline Characters ' \n ' or ' \r\n ' You can use the PHP newline characters \n or \r\n to create a new line inside the source code. However, if you want the line breaks to be visible in the browser too, you can use the PHP nl2br() function which inserts HTML line breaks before all newlines in a string.

Can we use \n in PHP?

?> Using new line tags: Newline characters \n or \r\n can be used to create a new line inside the source code.

Can we use echo in PHP?

The PHP echo StatementThe echo statement can be used with or without parentheses: echo or echo() .

What does N mean in PHP?

\n is the newline or linefeed, other side \r is the carriage return. They differ in what uses them. Windows uses \r\n to signify the enter key was pressed, while Linux and Unix use \n to signify that the enter key was pressed.


2 Answers

Use the PHP_EOL constant, which is automatically set to the correct line break for the operating system that the PHP script is running on.

Note that this constant is declared since PHP 5.0.2.

<?php     echo "Line 1" . PHP_EOL . "Line 2"; ?> 

For backwards compatibility:

if (!defined('PHP_EOL')) {     switch (strtoupper(substr(PHP_OS, 0, 3))) {         // Windows         case 'WIN':             define('PHP_EOL', "\r\n");             break;          // Mac         case 'DAR':             define('PHP_EOL', "\r");             break;          // Unix         default:             define('PHP_EOL', "\n");     } } 
like image 95
Andrew Moore Avatar answered Oct 12 '22 01:10

Andrew Moore


  • \n is a Linux/Unix line break.
  • \r is a classic Mac OS (non-OS X) line break. Mac OS X uses the above unix \n.
  • \r\n is a Windows line break.

I usually just use \n on our Linux systems and most Windows apps deal with it ok anyway.

like image 32
Jarod Elliott Avatar answered Oct 12 '22 00:10

Jarod Elliott