PHP Return
The return statement in PHP allows you to return a value from the function. If you want to return a value from the PHP function, you can use the return keyword, followed by the value to be returned.
The return statement immediately stops the execution of a function and optionally returns a value (or data) back to the part of the code where the function was called. This makes the return statement an essential feature for creating reusable and dynamic functions in PHP.
Syntax of PHP Return Statement
To return a value from a function, you simple type return followed by the value you want to return. The general syntax to return a value from a PHP function is as:
return return_value;
Here, return is a keyword in PHP. When the return statement is encountered inside the function, the function stops executing and returned the specified value to the caller of the function. However, using the return statement is optional. If it is omitted, the function will return a NULL by default.
To capture this return value, you can define a variable and assign the function call to it. The variable will store the value returned by the function for the further use. The general syntax is as:
$VariableName = function_Name();
Basic Example of Return Statement
Let’s take some basic examples based on the PHP return statement.
Example 1: Returning a number
<?php
// Function declaration to add two numbers.
function add($a, $b) {
return $a + $b; // return statement.
}
// Calling the function with passing argument values.
$result = add(5, 7);
echo "Sum of two numbers = $result";
?>
Output: Sum of two numbers = 12
In this example, we have defined a function named add() that takes two parameters $a and $b. Inside the function, we have written the logic of calculating the sum of two numbers and returned its result to the caller of the function. When we called the add() function, we have assigned the returned value to a variable named $result. Then, we have displayed the result.
Example 2: Let’s write a PHP program to calculate the average of three numbers. Also, function should return the average.
<?php
// Declare a function to find average of three numbers.
function calc_avg($n1, $n2, $n3) {
$avg = ($n1 + $n2 + $n3) / 3;
return $avg; // return statement.
}
// Call the function, pass arguments and accept return value.
$result = calc_avg(5, 7, 10);
echo "Average of three numbers = $result";
?>
Output: Average of three numbers = 7.3333333333333
In this example, we have defined a function named calc_avg() that takes three parameters $n1, $n2, and $n3, respectively and returns the average of three numbers to the calling function. You can also use value retuned by the calc_avg() function without storing it in a variable like this:
echo "Average of three numbers = " . calc_avg(5, 7, 10);
Example 3: Return a string value
<?php
function greet($name) {
return "Hello, " . $name . "!";
}
// Capturing the returned string in a variable named $message.
$message = greet("Alice");
echo $message . "\n";
// Using the returned string value directly.
echo greet("Bob");
?>
Output: Hello, Alice! Hello, Bob!
Example 4: No value returned
<?php
function doNothing() {
return; // Returning no value.
}
var_dump(doNothing());
?>
Output: NULL
How to Return an Array from PHP Function?
A function in PHP can return only a single value with the return keyword. To return more than one value, you can return an array from a function.
Example 5:
<?php
function getFruits() {
return ["Apple", "Banana", "Cherry", "Orange"]; // Returning an array.
}
// Calling function.
$fruits = getFruits();
print_r($fruits);
?>
Output: Array ( [0] => Apple [1] => Banana [2] => Cherry [3] => Orange )
How to Return Function from PHP Function?
In PHP, you can return a function using a callable or closure as an anonymous function. This form allows you to return a function from another function. This is called higher-order function. A higher-order function is a function that returns another function or accepts a function as an argument. Let’s take some examples based on it.
Returning an Anonymous Function (Closure)
Example 6:
<?php
function createGreetingFunction() {
// Returning anonymous function.
return function ($name) {
return "Hello, " . $name . "!";
};
}
// Calling the function.
$greet = createGreetingFunction();
// Invoking returned function with passing arguments.
echo $greet("Alice") . "\n";
echo $greet("Bob");
?>
Output: Hello, Alice! Hello, Bob!
In this example, we have defined a function named createGreetingFunction() that returns an anonymous function (closure). An anonymous function has no name, and it is defined using the function keyword.
The returned function takes one parameter, $name, and returns a greeting string. When createGreetingFunction() function is called, PHP executes and returns the anonymous function inside it. Then, we have assigned the returned function to the variable named $greet.
Now, $greet holds the returned anonymous function, which we can invoke like any other function. In the above code, $greet() is now a callable function. We have called $greet(“Alice”) which passes “Alice” as the $name parameter to the anonymous function, which returns “Hello, Alice!”.
The function createGreetingFunction() is an example of a higher-order function because it returns a callable function.
Returning a Named Function as a Callable
You can return the name of an existing function as a string and use it as a callable.
Example 7:
<?php
function getMathOperation() {
// Returning a named function as a string.
return "addNumbers";
}
function addNumbers($a, $b) {
return $a + $b;
}
// Calling the high-order function.
$operation = getMathOperation();
echo $operation(50, 10);
?>
Output: 60
In this example, we have defined a function named getMathOperation() that returns the name of another function “addNumbers” in the form of string. This means the return value is the string “addNumbers”, which represents the name of the function.
In PHP, you can call a function dynamically using its name as a string. The returned addNumbers() function takes two parameters, $a and $b, and returns the sum of them. When getMathOperation() function is called, PHP executes and returns the string “addNumbers”, which is a named function. Then, we have assigned the returned string (function name) to a variable $operation.
Now, the variable $operation holds the string “addNumbers”, but when called, it acts as a callable function. In the above code, $operation() is now a callable function. We have called $operation(50, 10) by passing arguments to the $a and $b parameters of the addNumbers() function. The addNumbers() function calculates the sum of two numbers and returns their sum.
How to Return Objects from Function in PHP?
PHP allows you to return objects from a function or method. You can do it by creating an object of a class and returning it using the return statement. Returning objects allows you to combine data and behavior in an object and pass it in the application program for further use.
The general syntax to return objects from a function in PHP is as:
<?php
class ClassName {
// Properties and Methods
}
function createObject() {
return new ClassName(); // Create and return an object.
}
$object = createObject(); // Capture the returned object
?>
Example 8: Returning Objects from a Function
<?php
// Define a class named Person.
class Person {
private $name;
private $age;
// Declare a constructor.
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
// Declare a method.
public function getDetails() {
return "Name: {$this->name}, Age: {$this->age}";
}
}
// Create a function.
function createPerson($name, $age) {
// Return an object of the Person class
return new Person($name, $age);
}
// Capture the returned object.
$person = createPerson("Saanvi", 18);
echo $person->getDetails(); // calling method.
?>
Output: Name: Saanvi, Age: 18
Using Return Statement in Conditional Statements
Let’s take some important examples where we will use the return statement in PHP conditional statements.
Example 9:
<?php
function divide($a, $b) {
if ($b === 0) {
return "Division by zero error!";
}
return $a / $b;
}
echo divide(10, 2) . "\n";
echo divide(10, 0);
?>
Output: 5 Division by zero error!
Example 10: Returning value based on conditions
<?php
function getDiscount($price) {
// Returning value based on the condition.
return $price > 100 ? 20 : 10;
}
echo getDiscount(150) . "\n";
echo getDiscount(80);
?>
Output: 20 10
How to Return Multiple Values in PHP?
PHP does not directly support returning multiple values, but you can achieve this by using one of the following techniques:
1. Using an Array
You can return an array containing multiple string values. You can then access each string individually.
Example 11:
<?php
function getStrings() {
return ["HTML", "CSS", "JavaScript", "PHP"];
}
$result = getStrings();
echo $result[0] . "\n";
echo $result[1] . "\n";
echo $result[2] . "\n";
echo $result[3];
?>
Output: HTML CSS JavaScript PHP
Example 12:
<?php
function calculate($a, $b) {
return [$a + $b, $a - $b];
}
list($sum, $difference) = calculate(10, 5);
echo "Sum: $sum, Difference: $difference";
?>
Output: Sum: 15, Difference: 5
2. Using Concatenated String
You can concatenate multiple strings into one and return the combined string. You can split each string using explode() function that splits the string into an array.
Example 13:
<?php
function getConcatenatedStrings() {
return "HTML,CSS,JavaScript,PHP";
}
// Calling the function.
$result = getConcatenatedStrings();
// Splits the string into an array using explode() function.
$strings = explode(",", $result);
// Displaying the results.
echo $strings[0] . "\n";
echo $strings[1] . "\n";
echo $strings[2] . "\n";
echo $strings[3];
?>
Output: HTML CSS JavaScript PHP
3. Pass Multiple Strings by Reference
If you don’t want to return an array of strings, you can pass multiple variables by reference and assign values to them within the function. Look at the example below:
Example 14:
<?php
function setStrings(&$str1, &$str2, &$str3) {
$str1 = "Hello";
$str2 = "World";
$str3 = "PHP";
}
setStrings($a, $b, $c);
echo $a;
echo $b;
echo $c;
?>
Output: HelloWorldPHP
4. Using an Associative Array for Named Strings
You can return multiple values from a function in PHP by using an associative array of multiple named strings.
Example 15:
<?php
function getNamedStrings() {
return [
"greeting" => "Hello",
"language" => "PHP",
"subject" => "Programming"
];
}
$result = getNamedStrings();
echo $result["greeting"] . "\n";
echo $result["language"] . "\n";
echo $result["subject"];
?>
Output: Hello PHP Programming
In this tutorial, you have learned about the return statement in PHP with syntax and basic examples. You also learned how to return a single value, an array, function, and multiple values from PHP functions.