Jump to content

Inside a function return vs echo


Audittxl

Recommended Posts

Always use return. Using echo will echo out the content where ever the function is called, so if you called the function before the header etc, it would display whatever you echo above the header.

 

Using return, you assign the function call to a variable for use later on in the code.

Link to comment
Share on other sites

return terminates a function block, echo just echoes it and continues function execution, so it will eventually return undefined. Which is mostly not what you want.

If you want functions to hold a variable throughout your program, always use return.

Link to comment
Share on other sites

If you are worried about using return because it stops the execution of the function and you want to output multiple things to the browser, either concatenate the strings or put them in an array and use return at the end of the function then print them at the appropriate point in the program.

Link to comment
Share on other sites

Return and echo do two different things:

 

Echo outputs directly to the browser.

 

Return stops function execution and sends a value back to the function's invocation context.  Example:

function example($x)
{
    return $x * $x;
}
 
$val = example(5); // $val now contains the value 25 (5 * 5)

Since both echo and return do different things, using them correctly merely depends on what you're trying to do at that moment.  Need to display data?  Use echo.  Need to use the value created after a function processes some data?  Use return.

 

That said, you'll likely return far more than echo.  Functions are supposed to be black boxes - you pass data in, the function works on it, and ultimately gives back a new value (or set of values).  Echoing generally is better used in your main script execution rather than functions.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.