Search code examples
phphtmlpre

Why does <pre> output differently when used in a one-line concatenated echo?


A small thing, but irritating. Why does this:

echo "<pre>".print_r($array)."</pre>";

...output this:

Array ( [0] => SP2 [1] => SP1 [2] => ennis123 )

Whereas, this:

echo "<pre>";
print_r($array_of_refs_for_rm);
echo "</pre>";

...outputs that:

Array
(
    [0] => SP2
    [1] => SP1
    [2] => ennis123
)

I'd simply like to save some vertical space in my code when debugging.


Solution

  • Because print_r() writes in the output.

    You can use the second parameter to redirect the output in the variable.

    echo "<pre>".print_r($array, true)."</pre>";
    

    In your case, the output was made before the <pre> tag.

    Note that the function var_export() has the same behavior.