How to Return Value from Function in PHP: Simple Guide
In PHP, you use the
return statement inside a function to send a value back to where the function was called. The syntax is return value;, which ends the function and outputs the specified value.Syntax
The return statement sends a value back from a function to the caller. It stops the function execution immediately and outputs the given value.
- return: keyword to send value back
- value: any data you want to return (number, string, array, etc.)
- ;: ends the statement
php
<?php function exampleFunction() { return 42; // returns the number 42 } ?>
Example
This example shows a function that returns the sum of two numbers. The returned value is stored in a variable and then printed.
php
<?php function add($a, $b) { return $a + $b; } $result = add(5, 7); echo $result; // Outputs 12 ?>
Output
12
Common Pitfalls
One common mistake is forgetting the return statement, which causes the function to return NULL by default. Another is placing code after return, which will never run because return ends the function immediately.
php
<?php // Wrong: no return, outputs nothing function noReturn() { $a = 5 + 5; } // Right: returns the value function withReturn() { $a = 5 + 5; return $a; } // Wrong: code after return never runs function afterReturn() { return 10; echo 'This will not print'; } ?>
Quick Reference
| Concept | Description |
|---|---|
| return | Sends a value back and ends the function |
| return value; | Returns the specified value |
| No return | Function returns NULL by default |
| Code after return | Will not execute |
Key Takeaways
Use
return to send a value back from a function in PHP.The
return statement ends the function immediately.If you omit
return, the function returns NULL by default.Avoid placing code after
return as it will never run.Store the returned value in a variable to use it later.