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.
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.
?> Using new line tags: Newline characters \n or \r\n can be used to create a new line inside the source code.
The PHP echo StatementThe echo statement can be used with or without parentheses: echo or echo() .
\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.
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"); } }
\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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With