PHP Echo Line Breaks

PHLAK picture PHLAK · Nov 1, 2008 · Viewed 97.7k times · Source

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

Andrew Moore picture Andrew Moore · Nov 1, 2008

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");
    }
}