How to Add a Newline Character to a PHP String?

You can add a newline character to a PHP string in the following ways:

Using the PHP_EOL Constant

PHP has a built-in constant (PHP_EOL) for adding newline character. Using this constant will add the correct "End Of Line" character that the platform (PHP is running on) supports (i.e. what the server OS supports). You can use it like so:

$str = 'Foo' . PHP_EOL . 'Bar';

echo $str;

// output:
// Foo
// Bar

Using the Newline Character in a Double-Quoted String

In PHP, only a double-quoted string interprets escape sequences (such as \n). Therefore, to add a newline character in PHP, you can simply use newline escape sequences (such as \r\n, \r or \n) in a double-quoted string, for example, like so:

$str = "Foo\r\nBar";

echo $str;

// output:
// Foo
// Bar

Using the chr() Function

You can specify, for example, the following character codepoints to the chr() function:

  • "\n" (ASCII 10 / 0x0A) — a new line (line feed);
  • "\r" (ASCII 13 / 0x0D) — a carriage return.

For example, you can add these characters using codepoints in hexadecimal number format like so:

$str = 'Foo' . chr(0x0D) . chr(0x0A) . 'Bar';

echo $str;

// output:
// Foo
// Bar

Similarly, you can add these characters using codepoints in decimal number format like so:

$str = 'Foo' . chr(13) . chr(10) . 'Bar';

echo $str;

// output:
// Foo
// Bar

The chr() function creates a one-character string in a single-byte encoding (such as ASCII, ISO-8859, or Windows 1252).

Please note that the chr() function is not aware of any string encoding, and cannot be passed a Unicode codepoint value to generate a string in a multibyte encoding such as UTF-8 or UTF-16.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.