I am trying to echo a string from a Recursive function:
echo \"
and
echo \"
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>";
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.