Returning values from a function is one of the most powerful features in PHP. It allows a function to process data internally and send the result back to the code that called it. This leads to cleaner, modular, and more efficient applications.
What Does “Returning Values” Mean?
A function can perform certain operations and then return the output using the return statement.
The returned value can be:
- a number
- a string
- an array
- an object
- or even another function’s result
Once a value is returned, the function stops executing.
Basic Syntax
function functionName() {
return value;
}
Example: Simple Return Value
function addNumbers($a, $b) {
return $a + $b;
}
$result = addNumbers(10, 20);
echo $result; // Output: 30
Example: Returning a String
function greet($name) {
return "Hello, $name!";
}
echo greet("Sagar");
Example: Returning an Array
function getUser() {
return ["name" => "Sagar", "role" => "Developer"];
}
$user = getUser();
print_r($user);
Returning Multiple Values (Using Array or List)
function calculate($a, $b) {
return [$a + $b, $a - $b, $a * $b];
}
list($sum, $diff, $prod) = calculate(10, 5);
echo $sum; // 15
Returning Early
You can stop a function anytime using return:
function checkAge($age) {
if ($age < 18) {
return "Not Eligible";
}
return "Eligible";
}
Why Are Return Values Important?
- Helps break logic into reusable parts
- Makes functions more powerful and flexible
- Supports clean and testable code
- Helps integrate complex data processing
Citations
🔗 View other articles about PHP:
http://savanka.com/category/learn/php/
🔗 External PHP Documentation:
https://www.php.net/manual/en/