what does comma in echo statement signify?

后端 未结 2 1516
误落风尘
误落风尘 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 "<li>", $node, writeList($arr), "</li>";
      

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

      echo "<li>";
      echo $node;
      echo writeList($arr);
      echo "</li>";
      

      But when you do this:

      echo "<li>" . $node . writeList($arr) . "</li>";
      

      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 "<li>", $node, writeList($arr), "</li>";
      $out = ob_get_clean();
      

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

      $out = "<li>" . $node . writeList($arr) . "</li>";
      
      0 讨论(0)
    • 2021-01-14 16:42

      echo is a language construct and can accept multiple arguments separated by a comma. The effect is identical to a concatenated string.

      The output shouldn't be different - I can't think of an instance where it could be.

      Edit: Ah, but it is. That is because your function echo()es stuff. In the first instance, <li> and $node get output; then the function's output comes.

      I would have WriteList simply return values recursively.

      0 讨论(0)
    提交回复
    热议问题