Question

I have heredoc string and I want to put the ++$var into the string. My code is actually much more complicated, but it simply looks like this:

t=0;
for(i=1;i<=20;i++){
echo <<<EOT
{++$t} somestring {$i}
{++$t} otherstring {$i}
{++$t} anotherstring {$i}
{++$t} nextstring {$i}
{++$t} endstring {$i}
EOT;
}

In for loop is numbered list with 5 lines, which are continuously repeated. And each 5 lines contain the same number $i from the loop. But the ++$t can't work this way. Any idea how to make it run?

Expected output:

1 somestring 1
2 otherstring 1
3 anotherstring 1
4 nextstring 1
5 endstring 1
6 somestring 2
7 otherstring 2
8 anotherstring 2
9 nextstring 2
10 endstring 2
11 somestring 3
...

Update (thanks for responses): There is no solution with heredoc. Better to use string concatenation and quotes. If there is a long text within heredoc field, best way is to use array for it.

Was it helpful?

Solution

With a concat method instead:

<?php

$array = array(
    'somestring',
    'otherstring',
    'anotherstring',
    'nextstring',
    'endstring'
);

$count = 0;
for ($i2 = 1; $i2 <= 20; $i2++)
    for ($i = 0; $i < count($array); $i++)
        echo ++$count . ' ' . $array[$i] . ' ' . $i2 . "\n";

Output:

1 somestring 1
2 otherstring 1
3 anotherstring 1
4 nextstring 1
5 endstring 1
6 somestring 2
7 otherstring 2
8 anotherstring 2
9 nextstring 2
10 endstring 2
11 somestring 3
[..truncated...]

OTHER TIPS

You can't write expressions inside heredoc style, you can just print variables without any additional operation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top