In PHP, what does "<<<" represent?
Asked Answered
R

8

83

For example:

$sql = <<<MySQL_QUERY
Reduplicate answered 13/9, 2010 at 11:40 Comment(3)
You can read the PHP documentation on the Heredoc syntax for a better understanding.Casket
If you need any other symbols explained, this is a good referenceNatelson
#5673769Australorp
C
90

That's heredoc syntax. You start a heredoc string by putting <<< plus a token of your choice, and terminate it by putting only the token (and nothing else!) on a new line. As a convenience, there is one exception: you are allowed to add a single semicolon after the end delimiter.

Example:

echo <<<HEREDOC
This is a heredoc string.

Newlines and everything else is preserved.
HEREDOC;
Cortisol answered 13/9, 2010 at 11:44 Comment(3)
What's the difference between this and a regular string? Why not just do echo "This is a heredoc....."Linares
@Imray as far as I can remember, you can put single and double quotes into the heredoc as well as variables and everything will work. If you want to use double quotes in your echo statement, you would have to escape them. Still, I stopped using heredoc pretty soon after I started, because I didn't like breaking my indentation patterns for it. Now I form many of my strings as arrays that I later implode("\n",$string_array).Jackdaw
I'd argue that it is pretty useful if you want to inject different languages. Being able to use newlines without concatenation (which might break code completion etc.) is really nice.Denunciatory
M
26

This is called a heredoc, and it lets you do a long piece of text that goes over several lines. You can put PHP variables in there and they will replace with the value. The word CHART can be anything. It just needs to be the same to start and stop where the quoted text begins.

You could do the same thing by appending multiple quoted strings, but this is cleaner most of the time for extended documents like this HTML text. There is also something called a nowdoc which is like a single quote string in PHP, but these won't let you use variables inside them.

Morrell answered 18/6, 2012 at 22:37 Comment(1)
Oh okay, thanks. instead of searching a long time I figured I would just ask a quick questionSyzygy
F
24

It is the start of a string that uses the HEREDOC syntax.

A third way to delimit strings is the heredoc syntax: <<<.

After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

Fruiter answered 13/9, 2010 at 11:42 Comment(4)
Cool, I didn't know that one... I read the link you sent and honestly, I understand why I could live without that one so far! ;) What would be the advantage of using that for a string?Gasper
@Gasper it allows you to use both kinds of quotations inside the string without breaking it: <<<END Hello "$name"! How is '$spouse' today? END One huge pain in the ass is, however, that the END marker must not be indented, so Heredoc content usually breaks your code's indentation. It's indeed not really one of PHP's most important features :)Fruiter
@YiJiang that was actually because of the german localization! Damn geolocation, always gives me the wrong link even though english is my browser language. Corrected, cheers :)Fruiter
@Gasper you're welcome. @Hugo does have a point, though, there are situations where they do make sense and help make the code more readable. But the missing indenting capability takes a lot away at least in my practiceFruiter
H
17

It's PHP's heredoc.

Example:

$sql = <<<MySQL_QUERY
SELECT * 
FROM TAB 
WHERE A = 1 AND B = 2 
MySQL_QUERY;           
Hexaemeron answered 13/9, 2010 at 11:42 Comment(0)
T
8

It's the heredoc syntax.

$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
Teratism answered 13/9, 2010 at 11:43 Comment(0)
N
8

It's a heredoc, for long strings that you don't have to worry about quotation marks and whatnot. If you notice the word CHART and then there's a line that says CHART;, that indicates the end of the string.

The important thing to remember when using this format is that whatever string you use to define the end of the string (such as CHART in this case), that word has to appear on a line on its own, followed by a semicolon, and NO characters can occur after the semicolon on the same line, even whitespace, otherwise PHP thinks it's part of the string.

Nador answered 18/6, 2012 at 22:38 Comment(0)
C
8

I found both Heredoc and Nowdoc extremelly powerfull and usefull in PHP and I am surprise that no one have so far give more example of what you can do.

First the difference between Heredoc and Nowdoc is simple,

  • Heredoc: Is like the "" double quote string you can put Variables
  • Nowdoc: Is like the '' single quote string no variable are parsed

For the following example I will only show the Heredoc, in order to make a Nowdoc just wrap the token inside single quotes -> 'TOKEN'.

Features and Advantages

  • The "" and '' can be added as much as needed and won't cause any errror
  • Easily output HTML code with dynamic variables, avoid usesell concatenations.
  • Store it in variables for letter use, can create small components and just output them.
  • The Lines are interpreted literally with '\n' hence is like writing in a doc, also useful to add
    with nl2br .

Simple Example

$a = "Hello";
$b = "World";
// HEREDOC
echo <<<HEREDOC
<strong> HEREDOC:  </strong> 
Variable A: "$a" 
Variable B: "$b"
HEREDOC;
echo '</br>';

// NOWDOC
echo <<<'NOWDOC'
<strong> NOWDOC:  </strong> 
Variable A: "$a" 
Variable B: "$b"
NOWDOC;

output

HEREDOC: Variable A: "Hello" Variable B: "World"
NOWDOC: Variable A: "$a" Variable B: "$b"

Recipes

  1. Use nl2br to add <br> for each line

This works because HEREDOC interpretes each \n as an actual line

   // HEREDOC
    echo nl2br(<<<HEREDOC
    <strong> HEREDOC:  </strong> 
    Variable A: "$a" 
    Variable B: "$b"
    HEREDOC);
    // Output HEREDOC:
    //Variable A: "Hello"
    //Variable B: "World"
  1. Create small components

         <?php
             foreach($tasks  as $task) {
                 // Create an HTML like component
                 $component = <<<HEREDOC
                 <div class="pure-u-1-3">
                     <div class="card">
                         <div class="card-header">
                            {$task['name']}
                         </div>
                         <div class="card-body">
                             <h5 class="card-title"> {$task['state']} </h5>
                             <p class="card-text"> {$task['description']} </p>
                             <a href="view?model=todo_list&task_id={$task['id']}" class="btn btn-primary">See Task Todos</a>
                         </div>
                     </div>                    
                 </div>
                 HEREDOC;
                 echo $component; // Output
    
             }
    
         ?>
    

Or just put in one string then output with 1 echo

    <?php
        $taskRendered = '';
        foreach($tasks  as $task) {
            // Create an HTML like component
            $component = <<<HEREDOC
            <div class="pure-u-1-3">
                <div class="card">
                    <div class="card-header">
                       {$task['name']}
                    </div>
                    <div class="card-body">
                        <h5 class="card-title"> {$task['state']} </h5>
                        <p class="card-text"> {$task['description']} </p>
                        <a href="view?model=todo_list&task_id={$task['id']}" class="btn btn-primary">See Task Todos</a>
                    </div>
                </div>                    
            </div>
            HEREDOC;
            $taskRendered .= $component;
        }
        echo $taskRendered; // Output
    
    ?>

Documentation

Comines answered 6/1, 2022 at 8:36 Comment(1)
Being a bit pedantic, in your first code block for Recipies should the HEREDOC); be HEREDOC;Cocaine
C
-1

To get a clear idea:

$data = array(
  "Id" => 12345,
  "Cutomer" => "hi",
  "Quantity" => 2,
  "Price" => 45
);

curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));

If we use <<<:

$data = <<<DATA
{
  "Id": 12345,
  "Customer": "John Smith",
  "Quantity": 1,
  "Price": 10.00
}
DATA;

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

Conclusion: If we go with the 1st method we have to convert it into json_encode() which somehow requires some processing. Instead, We can use the <<< operator to save some time and get some clean code. :)

Casque answered 29/12, 2020 at 17:36 Comment(1)
The <<< example is certainly not clean code. I wouldn't recommend anyone to construct array data using heredoc.Toxicant

© 2022 - 2025 — McMap. All rights reserved.