PHP – assign multi lines string to a variable

PHP supports Heredoc and Newdoc syntax. It is a convenient way to assign multiple lines string to a variable. This makes code more readable. Here is quick code snippets for it.

Using php heredoc

<?php
$a = "hello";
$s = <<<EOM
Line1
$a
Line2
EOM;
echo "==========\n";
echo $s;
echo "==========\n";
?>
==========
Line1
hello
Line2==========
Env: PHP 5.5.9 (Linux)

Few points about PHP heredoc

  1. Heredoc identifier can be anything. The closing heredoc identifier must start in the beginning of line and end with ;
  2. Last newline does not become part of variable.
  3. Other variables get evaluated in heredoc

Using php newdoc

Newdoc is similar to heredoc but variables are not expanded. This is useful for assigning code snippets etc. Newdoc beginning identifier is within single quotes. Example and outcome using newdoc:

<?php
$a = "hello";
$s = <<<'EOM'
Line1
$a
Line2
EOM;
echo "==========\n";
echo $s;
echo "==========\n";
?>
==========
Line1
$a
Line2==========
Env: PHP 5.5.9 (Linux)

Note that $a is not expanded with newdoc syntax.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments