PHP return Statement


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

 Live Demo

<?php
function SayHello(){
   echo "Hello World!
"; } echo "before calling SayHello() function
"; 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

 Live Demo

<?php
function square($x){
   return $x**2;
}
$num=(int)readline("enter a number: ");
echo "calling function with argument $num
"; $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

 Live Demo

//main script
<?php
echo "inside main script
"; echo "now calling test.php script
"; include "test.php"; echo "returns from test.php"; ?> //test.php included <?php echo "inside included script
"; 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

 Live Demo

//main script
<?php
echo "inside main script
"; echo "now calling test.php script
"; $result=include "test.php"; echo $result; echo "returns from test.php"; ?> //test.php included <?php $var="from inside included script
"; return $var; ?>

Output

This will produce following result −

inside main script
now calling test.php script
from inside included script
returns from test.php

Updated on: 18-Sep-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements