Search code examples
phpheredoc

How to use a PHP heredoc as an array value?


I've a larger piece of multi-line text that I need to put in an PHP associative array through a here-doc. It looks like this:

    $data = [
      "x" => "y",
      "foo" => "bar",
      /* ... other values ... */
      "idx" => <<< EOC
data data data data
data data data data
data data data data
EOC;
      "z" => 9,
      /* ... more values ... */
    ];

I can't figure out how to provide $data["idx"] the multi-line text with a heredoc.


Solution

  • You can't end it with a semicolon at the end of the heredoc identifier. In PHP 7.2 and earlier the comma needs to be on a new line. It has to look like this:

    $data = [
      "x" => "y",
      "foo" => "bar",
      /* ... other values ... */
      "idx" => <<<EOC
    data data data data
    data data data data
    data data data data
    EOC
     , "z" => 9,
     /* ... more values ... */
    ];