Monday, July 5, 2010

Difference between echo & return statements in function

Hi,
Here is the explanation about where we should use echo and where we should use return statements while working with functions.

If you want to print some thing on browser and continue execution of the process then you have to use echo statement.
Ex:

Recursive functions with static variables


function test()
{
static $count = 0;

$count++;
echo $count;
if ($count < 10) {
test();
}
$count--;
}
test();
?>
Here static variable is initialised only once when first called the test function and then it will maintain the value of $count till the end of the process.
O/P:12345678910

When you use the return statement the program execution stopped in that line and output some thing to the variable. So Calling return in your script or function will either end the script or end the function and then return the value
Ex:
function test($arg)
{
if ( $arg == 'ban' ) {
return 'Banana';
}
else
{
// There's nothing else to do, so end execution of this function
return;
}
}
$fruit = test('banana');
if ($fruit=='Banana')
{
echo 'Banana';
}
?>

No comments: