How to handle multi-line strings in PHP

PHP has great support for multi-line strings, so you can create multi-line strings in many ways.

First, you can simply put a line break in the string itself as shown below:

<?php

$str = "Hello!
This is a multi-line strings.
You can add a line break between the sentences.";

print $str;

When you run PHP using the terminal, the output will preserve the line breaks:

Hello!
This is a multi-line strings.
You can add a line break between the sentences.

You can also create multi-line strings by adding escape sequences in the string.

Consider the following example:

<?php

$str = "Hello!\n";
$str .= "This is a multi-line strings.\n";
$str .= "You can add a line break between the sentences.";

print $str;

In the example above, the strings are concatenated using the .= symbol.

To add a line break, the escape sequence character \n is added.

Finally, you can also replace the escape sequence character with the PHP_EOL constant as shown below:

<?php

$str = "Hello!" . PHP_EOL;
$str .= "This is a multi-line strings." . PHP_EOL;
$str .= "You can add a line break between the sentences.";

print $str;

The PHP_EOL constant allows PHP to insert the escape sequence character that matches the operating system where that PHP code is executed.

Keep in mind that the line breaks will be ignored when you open the PHP page from the browser.

To preserve the line breaks on the browser, you need to add the <br> tag right where you want to add a line break:

<?php

$str = "Hello!<br>
This is a multi-line strings.<br>
You can add a line break between the sentences.";

print $str;

But the <br> tag will be printed as it is when you run PHP from the command line.

You can’t create multi-line strings that work in both environments, so you need to use the solution that fits your conditions.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.