mamelepera mamelepera - 4 months ago 9
PHP Question

Make function inside echo be outputted at formatted position

I have tried many approaches to get this right, including all types of quoting, etc. I will give you my current code before explaining the situation.

function show_msgs($msgs)
{
foreach($msgs as $msg) {
echo '<div class="msg">' . $msg . '</div>' . "\n ";
}
}

function generate_msgBox()
{
global $array;

$stackoverflow =
<<<EOT
<div class="container">
<div class="msgBox">
%s
</div>
</div>
EOT;

$stackoverflow = sprintf($stackoverflow, show_msgs($array));

echo $stackoverflow;
}


generate_msgBox function currently outputs this when called:

<div class="msg">First message!</div>
<div class="msg">Seconds message!</div>

<div class="container">
<div class="alertBox">

</div>
</div>


However I need it to output this:

<div class="container">
<div class="alertBox">
<div class="msg">First message!</div>
<div class="msg">Seconds message!</div>
</div>
</div>


I tried putting function directly inside echo that is enclosed by normal quotes and I got the same result.

How do I fix this?

Answer

Echo in show_msgs function works before output of generate_msgBox function - when you call it. just return string with result of function

function show_msgs($msgs)
{
    $ret = '';
    foreach($msgs as $msg) {
        $ret .= '<div class="msg">' . $msg . '</div>' . "\n    ";
    }
    return $ret;
}
Comments