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.

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.

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.

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.