Use of increment operator in heredoc
Use of increment operator in heredoc
I want to increase the value of a variable by using the increment operator in heredoc. My current code is given below...
$counter = 0;
for($i = 0; $i<10; $i++):
echo <<< EOT
$counter++ <br/>
EOT;
endfor;
Its output is...
0++
0++
.
.
Mean post-increment operator is not working.
I have also tried pre-increment, like given below...
echo <<< EOT
++$counter <br/>
EOT;
Its output is...
++0
++0
.
.
Mean pre-increment operator is also not working.
I have also tried to put increment operation inside curly braces, like given below...
echo <<< EOT
++$counter <br/>
EOT;
But again no luck. Output is....
++0
++0
.
.
I have also searched it on google but didn't find anything useful.
I know if I can increase value before heredoc then I can print it in here doc correctly
$counter = 0;
for($i = 0; $i<10; $i++):
++$counter;
echo <<< EOT
$counter <br/>
EOT;
endfor;
It works fine.
But I want to use increment operator in heredoc, just like we use in case of single or double quoted with echo
.
echo
But it seems like heredoc doesn't support increment operation.
$var
$countupfunc($counter)
$i
So, you found out that heredoc does not support incrementing variables. Do you have a question?
– u_mulder
Sep 12 '18 at 6:52
No, I didn't find it. I supposed it for now.
– Shujaat
Sep 12 '18 at 6:53
@mario I can use
$i
, but proper name increase readability of code.– Shujaat
Sep 12 '18 at 6:54
$i
1 Answer
1
The complex/curly variable syntax $var…
does only allow variable access expressions, but not PHP expressions per se.
$var…
$var[…]
$var(…)
$var->prop…
$stat::$lookup
There can't be arithmetic operators within the +
itself. But only between
[…]
or (…)
used alongside.
[…]
(…)
One common workaround is to utilize variable function names:
$func = "htmlspecialchars"; // or any other no-op function
echo <<<HEREDOC
counter = $func($counter++)
HEREDOC;
Where you can easily use full expressions in the curly var syntax.
"There can't be arithmetic operators within the + itself. But only between […] or (…) used alongside." Can you please provide any reference?
– Shujaat
Sep 12 '18 at 7:02
See the manual link. Though it's only described with more examples there, it lists the various allowed expressions.
– mario
Sep 12 '18 at 7:04
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
$var
works really just for limited variable access expressions. Something like$countupfunc($counter)
e.g. Albeit this looks like an abstracted example, couldn't you just use$i
anyway?– mario
Sep 12 '18 at 6:50