0
0
PHPprogramming~5 mins

Heredoc and nowdoc syntax in PHP

Choose your learning style9 modes available
Introduction

Heredoc and nowdoc let you write long text easily in PHP without lots of quotes or dots.

When you want to write a big block of text or code inside PHP.
When you need to keep the text format exactly as you type it.
When you want to include variables inside text easily (heredoc).
When you want to write text exactly as is, without PHP changing anything (nowdoc).
When you want to avoid escaping quotes inside a string.
Syntax
PHP
<<<'LABEL'
Your text here
LABEL;

Heredoc starts with <<<LABEL and ends with LABEL; on a new line.

Nowdoc is like heredoc but uses single quotes: <<<'LABEL'.

Examples
Nowdoc example: text is exactly as typed, no variable replacement.
PHP
<<<'EOD'
This is nowdoc text.
Variables like $var are not replaced.
EOD;
Heredoc example: variables like $name will be replaced with their values.
PHP
<<<EOT
Hello $name!
Welcome to heredoc.
EOT;
Heredoc without quotes around label, variables inside will be parsed.
PHP
$text = <<<TEXT
This is heredoc.
It can span multiple lines.
TEXT;
Sample Program

This program shows heredoc replacing the variable $name with "Alice" and nowdoc printing the text exactly as is.

PHP
<?php
$name = "Alice";
$heredoc = <<<HEREDOC
Hello, $name!
This is heredoc syntax.
HEREDOC;

$nowdoc = <<<'NOWDOC'
Hello, $name!
This is nowdoc syntax.
Variables are not parsed here.
NOWDOC;

echo $heredoc;

echo $nowdoc;
OutputSuccess
Important Notes

The closing label must be at the start of the line with no spaces or tabs before it.

Heredoc acts like double quotes, so variables and escape sequences work.

Nowdoc acts like single quotes, so no variable parsing or escape sequences.

Summary

Heredoc and nowdoc help write long strings easily in PHP.

Use heredoc to include variables inside the text.

Use nowdoc to keep text exactly as typed, no variable replacement.