Introduction
The purpose of return statement in PHP is to return control of program execution back to the environment from which it was called. Upon returning, execution of expression following the one which invooked other function or module.
If return statement occurs inside a function, execution of current function is terminated, handing over the control back to the environment from which it was called. The return statement may have an exprssion as optional clause in front of it. In that case, value of the expression is also returned in addition to the control.
If encountered in an included script, execution of current scripts ends immediately and control goes back to the script which has included it. If it is found in the top level script itself, the execution ends immdeiately, handding back the control to the OS.
return in a function
Following example shows return statement in a function
Example
<?php function SayHello(){ echo "Hello World!\n"; } echo "before calling SayHello() function\n"; SayHello(); echo "after returning from SayHello() function"; ?>
Output
This will produce following result −
before calling SayHello() function Hello World! after returning from SayHello() function
return with value
In following example, a function returns with an expression
Example
<?php function square($x){ return $x**2; } $num=(int)readline("enter a number: "); echo "calling function with argument $num\n"; $result=square($num); echo "function returns square of $num = $result"; ?>
Output
This will produce following result −
calling function with argument 0 function returns square of 0 = 0
In next example, test.php is included and has return ststement causing control go back to calling script.
Example
//main script <?php echo "inside main script\n"; echo "now calling test.php script\n"; include "test.php"; echo "returns from test.php"; ?> //test.php included <?php echo "inside included script\n"; return; echo "this is never executed"; ?>
Output
This will produce following result when main script is run from command line−
inside main script now calling test.php script inside included script returns from test.php
There can be a expression clause in front of return statement in included file also. In following example, included test.php returns a string to main script that accepts and prints its value
Example
//main script <?php echo "inside main script\n"; echo "now calling test.php script\n"; $result=include "test.php"; echo $result; echo "returns from test.php"; ?> //test.php included <?php $var="from inside included script\n"; return $var; ?>
Output
This will produce following result −
inside main script now calling test.php script from inside included script returns from test.php