what does comma in echo statement signify?

后端 未结 2 1529
误落风尘
误落风尘 2021-01-14 15:50

I am trying to echo a string from a Recursive function:
echo \"

  • \", $node, recurse($arr), \"
  • \";
    and
    echo \"
  • \" .
  • 2条回答
    •  独厮守ぢ
      2021-01-14 16:27

      EDIT: OK, I get it. The culprit is your writeList() function. There is a secondary echo inside that function.

      When you do this:

      echo "
    • ", $node, writeList($arr), "
    • ";

      Each part is evaluated first and then printed out. It is equivalent to:

      echo "
    • "; echo $node; echo writeList($arr); echo "
    • ";

      But when you do this:

      echo "
    • " . $node . writeList($arr) . "
    • ";

      The entire string is constructed using the concatenation operators . first, then printed out. This means writeList($arr) is called first during the construction of the string, then the outer echo is called.

      To avoid this problem, don't echo anything within your function calls. Build strings using the concatenation operator and then return them so that your outer echo can print them.


      what if rather than echoing the strings, I want to store the string generated from this function in a variable. I am, particularly, interested in the output received from the first echo statement.

      Use output buffering.

      ob_start();
      echo "
    • ", $node, writeList($arr), "
    • "; $out = ob_get_clean();

      But for that particular statement, why not just concatenate instead?

      $out = "
    • " . $node . writeList($arr) . "
    • ";

    提交回复
    热议问题