PHP Reference ยท Language Constructs and Statements
PHP return statement
Reference for PHP return: send a value back from a function, end a function early, return types, multiple values via arrays, and returning from included files.
return ends the current function and hands a value back to the caller. Any code after it in that function is skipped. A function that reaches its end without return, or uses a bare return;, gives back null.
At the top level of a script, return stops the script. In an included file it ends that file and becomes the value of the include expression, which is the basis of simple configuration files.
function double(int $n): int { return $n * 2; }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
return; return expression;
| Name | Description |
|---|---|
expression |
Optional. The value handed to the caller (or to include when used at file level). |
Return value: the value of expression, or null when omitted.
Errors: with a declared return type, a value of the wrong type throws TypeError (after coercion in non-strict files). A void function may not return a value, a function declared never may not return at all, and an empty return; in a function with a non-void return type is a compile-time error.
Usage notes
- Return one value. To give back several, return an array (or an object) and unpack it with destructuring.
- Return types. Declare them (
: int,: ?string,: void,: never,: static). Without a declaration, PHP accepts anything. See type declarations. - Early returns keep functions flat: handle error and edge cases first, then do the main work.
- Return by reference needs
function &name()and a reference assignment at the call site. It is rarely needed. finallywins. Areturninsidefinallyoverrides areturnor exception fromtry. See try, catch, finally.- Generators use
returnto set the generator's final value, read withgetReturn(). - In included files,
return [...]lets$config = require 'config.php';work. See include and require. - Parentheses are optional;
return ($a);equalsreturn $a;. - To end the entire program from inside a function, use
exit.