PHP Tutorials

PHP Heredoc and Nowdoc: Write Cleaner Multiline Strings

Heredoc and nowdoc make long PHP strings easier to read and safer to write. This lesson shows how both syntaxes work with practical examples.

Serhat ALPASLAN2 min read

PHP

 

We’ll look at how to use heredoc and nowdoc to make PHP code more readable. I can tell you that you definitely need to learn them. When using variables in PHP, you sometimes need to use double quotes. To escape them, you need to use the \ character. To avoid this situation and reduce the chance of making mistakes, PHP gives us two nice features: heredoc and nowdoc. Now let’s look at them with an example;

<?php

$he = 'Ali';
$she = 'Zeynep';

$text = "$he dedi ki, \"PHP ile yeni bir proje yapacağım yardım edermisin\".
\"Tabiki .\" $she birlikte yapabiliriz .";

echo $text;
?>

As you can see in the example above, we needed to use variables inside a string, but we were able to add them using \ characters. We can’t say the usage above is wrong, but we can write it in a more readable and cleaner way. This way, when you look at your code a few months later, you’ll see that it’s cleaner. Now let’s rewrite it in a cleaner way using heredoc.

<?php
$he = 'Ali';
$she = 'Zeynep';

$text = <<<TEXT
$he dedi ki PHP ile yeni bir proje yapacağım yardım edermisin.
Tabiki . $she birlikte yapabiliriz ..
TEXT;

echo $text

?>

It’s obvious that the example above is simpler, and it will also make things easier for you and reduce the chance of making mistakes. You might ask: “Can I use single or double quotes inside this text?” Yes, you absolutely can, and you don’t need to do anything else to use them.

How Does Heredoc Work?

As you’ll see in the image below, first you need to add the <<< operator, and immediately after it write an identifier. This identifier can be any word. Then add your text and the variable you use inside it, and write the identifier again at the end of the text.

heredoc

When using an identifier inside heredoc, it must contain only alphanumeric characters and underscores, and it must start with a character that is not an underscore or a digit. When using the closing identifier:

  • It must start in the first column of the line.
  • It must not contain any characters other than a semicolon (;).
  • The character before and after the closing identifier must be a newline character.

For more information, you can visit the PHP website.

Share it if it helped

Write a comment