Dird Dird - 11 months ago 40
HTML Question

echo or return from a function

I have a function which echos out common code for a web page. If I do the code like this:

echo '<tr>';
CSCell("{$row['home_team']}/{$row['home_team']}",'home_home',$row, 1);
echo '</tr><tr>';
CSCell("{$row['home_team']}/Draw",'home_draw',$row, 1);
echo '</tr><tr>';

It works without issue. If I do it like this:

echo '<tr>' . CSCell("{$row['home_team']}/{$row['home_team']}",'home_home',$row, 1) . '</tr>';
echo '<tr>' . CSCell("{$row['home_team']}/Draw",'home_draw',$row, 1) . '</tr>';

It outputs an additional empty row for each line of code. Presumably it initially echos <tr> then the function outputs data then it returns
(because no return specified) then it begins the echo again (without re-calling the function & prints <tr>empty string</tr>).

How to stop it re-echoing the
HTML? The function only contains
echo data?

I'm too lazy to make it return now because of the other parts it is referenced in where it needs to echo. How to modify the function so it can be used to echo and return?

Answer Source

Since you are already relying on the output in other code, just add a fifth parameter to the function to tell it to echo or return:

function CSCell($a, $b, $c, $d, $return=false) {
    // build $output
    if($return) { return $output; }
    echo $output;

Then call it with $return = true:

echo '<tr>' . CSCell("{$row['home_team']}/Draw", 'home_draw', $row, 1, true) . '</tr>';

If you can't modify the function, then build a wrapper and buffer the output and return. I don't know what the function looks like so you need to check the arguments or rely on the CSCell() function to validate them:

function _cscell($a, $b, $c, $d) {
    CSCell($a, $b, $c, $d);
    return ob_end_clean();

Then call the wrapper function:

echo '<tr>' . _cscell("{$row['home_team']}/Draw", 'home_draw', $row, 1) . '</tr>';