PHP return Statement

The return statement in PHP is used to return control of program execution back to the environment from which it was called. Upon returning, execution continues with the statement following the function call.

When a return statement occurs inside a function, execution of that function terminates immediately, passing control back to the calling code. The return statement can optionally include an expression, in which case the value of that expression is returned along with control.

If a return statement is encountered in an included script, execution of that script ends immediately and control returns to the script that included it. If found in the main script itself, execution terminates and control returns to the operating system.

Return in a Function

The following example demonstrates a basic return statement in a function −

<?php
function SayHello(){
    echo "Hello World!
"; return; // Optional - function returns automatically at end } echo "before calling SayHello() function
"; SayHello(); echo "after returning from SayHello() function"; ?>
before calling SayHello() function
Hello World!
after returning from SayHello() function

Return with Value

Functions can return values using expressions. Here's an example −

<?php
function square($x){
    return $x ** 2;
}
$num = 5;
echo "calling function with argument $num
"; $result = square($num); echo "function returns square of $num = $result"; ?>
calling function with argument 5
function returns square of 5 = 25

Return in Included Files

When using include or require, the return statement can terminate execution of the included file. Since we cannot demonstrate file inclusion in this environment, here's how it conceptually works −

// main.php
<?php
echo "inside main script
"; echo "now calling test.php script
"; include "test.php"; echo "returns from test.php"; ?> // test.php <?php echo "inside included script
"; return; // Stops execution here echo "this is never executed"; ?>

Return Values from Included Files

Included files can also return values to the calling script −

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

Key Points

Context Behavior Can Return Value
Function Terminates function execution Yes
Included File Terminates file execution Yes
Main Script Terminates entire program No

Conclusion

The return statement is essential for controlling program flow and passing data between functions and included files. It immediately terminates execution in its current scope and optionally returns a value to the calling code.

Updated on: 2026-03-15T09:16:21+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements