Multiline Strings
In PHP, you can create multiline strings using different methods. The two most common ways are using Heredoc and Nowdoc syntaxes. Below are examples of each:
Heredoc Syntax
Heredoc syntax allows for the creation of multiline strings and supports variable interpolation.
<?php
$name = "John";
$heredocString = <<<EOD
This is a multiline string.
It can span multiple lines.
Hello, $name!
EOD;
echo $heredocString;
// Outputs:
// This is a multiline string.
// It can span multiple lines.
// Hello, John!
?>
Nowdoc Syntax
Nowdoc syntax is similar to Heredoc but does not parse variables. It is useful when you want to output a large block of text without any variable interpolation.
<?php
$nowdocString = <<<'EOD'
This is a multiline string.
It can span multiple lines.
Hello, $name!
EOD;
echo $nowdocString;
// Outputs:
// This is a multiline string.
// It can span multiple lines.
// Hello, $name!
?>
Multiline Strings Using Double Quotes
While not as clean as Heredoc or Nowdoc, you can also create multiline strings using double quotes and line breaks.
<?php
$multilineString = "This is a multiline string.
It can span multiple lines.
Hello, John!";
echo $multilineString;
// Outputs:
// This is a multiline string.
// It can span multiple lines.
// Hello, John!
?>
Example with HTML
Multiline strings are often used to generate dynamic HTML content.
<?php
$title = "Welcome";
$content = "This is a dynamic webpage.";
$html = <<<HTML
<!DOCTYPE html>
<html>
<head>
<title>$title</title>
</head>
<body>
<h1>$title</h1>
<p>$content</p>
</body>
</html>
HTML;
echo $html;
// Outputs the complete HTML document with the dynamic content
?>
These methods allow you to handle multiline strings efficiently and are useful for embedding large blocks of text or code in your PHP scripts.