0

PHP allows to declare a string on multiple lines as following:

$s = <<<EOS
    Hello
    World!
EOS;

Is is possible to use that notation to declare an array of strings? I'd like to write a code such as the following one (that is of course not working):

$data = array(<<<EOS
    Hello
    World!
EOS;, 
<<<EOS
    Hello
    Me!
EOS;);
6
  • 1
    Delete ; after EOS from your array Commented Jun 10, 2016 at 12:41
  • Oh yes, it's also working by removing all the ; after the EOS! Thanks! Commented Jun 10, 2016 at 12:48
  • @pes502 I get errors and/or the wrong output without additional modification as shown in my answer. Commented Jun 10, 2016 at 12:53
  • @MonkeyZeus I don't see any errors, but the output is bugged. So you really need to add coma and ); (array ending) to the separate lines. +1 for you Commented Jun 10, 2016 at 12:56
  • I am testing at sandbox.onlinephpfunctions.com with PHP 7.0.5 and closing the array on the same line as the closing EOS, like this EOS);, produces a parse error. Commented Jun 10, 2016 at 13:18

2 Answers 2

5

Certainly you can:

<?php
$a = array(<<<EOS
    foo
    bar!
EOS
, // comma here is important
<<<EOS
    bar
    foo!
EOS
); // closing the array on a separate line is important

print_r($a);

See Example #3 at http://php.net/manual/en/language.types.string.php


This works too by the way:

<?php
$a = array(
    'foo
    bar!',
    'bar
    foo!'
);

print_r($a);
Sign up to request clarification or add additional context in comments.

Comments

0

I use templates for long text:

     $data = array(file_get_contents('file1.txt'),  
file_get_contents('file2.txt')
    );



 print_r($data);exit;

file1.txt content

"sample line1"

file2.txt content

"sample line2 end of line

"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.