PHP Heredoc And When To Use And Its Usecase

Hello devs,

In this PHP example tutorial, I will discuss PHP heredoc and nowdoc. From this tutorial, you will learn about PHP heredoc and nowdoc. You will also learn from how to use PHP heredoc and when to use this.

We can use PHP heredoc and nowdoc strings to improve the readability of the code. PHP 7.3 released these interesting changes to the existing heredoc and nowdoc syntaxes. Let's see the usecase of PHP heredoc.

Syntax of PHP Heredoc

 

Now see the example of PHP heredoc.  Let assume that we have a string inside multiple quoted string. What will we do to print that? If a string contains the double quotes (“), we need to escape them using the backslash character(\).  Such as:

$he = 'A';
$she = 'B';

$text = "$he said, \"CodeCheef is awesome\".
\"Of course.\" $she agreed.";

echo $text

 

Output of this code is:

A said, "CodeCheef is awesome".
"Of course." B agreed.

 

Now we can do the same thing using PHP heredoc. Let's see the example of PHP here doc:

 

It will return the same output. Hope it can help you.

 

#php