Search code examples
phpfunctionreturn-valueecho

when using 'echo' in function, why does result appear on previous line?


I wrote up a function that echoed out the id at the otherside of a linked table.

when I write in the page that's calling the function--

echo "<br/>getalbumartistfunction: ".get_albumartistid($thisalbum);

it returns the artist_id number on the line above where I have that function call. So I went into the function and switched it from 'echo' to 'return' and it now appears right after the colons like I would expect (and is probably more along the lines of what I need).

So it works. But I am extremely confused why it would show the result on the previous line when the function is set to echo it.


Solution

  • The echo in the get_albumartistid is executed immediately when the function is called while the echo "
    ..." assembles the string before echoing it - essentially buffering the entire thing before it echoes. Return instead of echo is the proper way to handle this since that would effectively replace the function call with the string returned. If you were to use echo you'd have to:

    echo "<br/>getalbumartistfunction: ";
    get_albumartistid($thisalbum);
    

    Which effectively becomes:

    echo "<br/>getalbumartistfunction: ";
    echo "<The artist id>";
    

    In your original example that order of execution makes it:

    echo "<The artist id>";
    echo "<br/>getalbumartistfunction: ";
    

    Since all echoes happen immediately when it's called and PHP is not done buffering your outer echo statement.