Skip to content

Returning values

Returning values
Returning values from a function in PHP is done using the return statement. The return statement allows you to specify a value or an expression to be sent back as the result of the function when it’s called. This returned value can then be used in other parts of your code.
Here’s the basic syntax of the return statement within a function:
phpCopy code
function functionName($parameter1, $parameter2, …) { // Function body // Code to perform a task or calculation return $result; // Return a value or expression }
Let’s break down how to use the return statement to return values from a function:
1.Specify the Value: Inside the function body, determine the value you want to return. This can be a variable, a calculation, or any expression that results in a value.
2.Use the return Statement: Use the return keyword followed by the value or expression you want to return. This statement signals the end of the function’s execution, and the specified value is sent back to the point where the function was called.
3.Use the Returned Value: When you call the function and assign it to a variable, the returned value can be stored in that variable for further use in your program.
Here’s an example demonstrating how to use the return statement to return a value from a function:
phpCopy code
function addNumbers($num1, $num2) { $sum = $num1 + $num2; return $sum; // Return the result of the addition } $result = addNumbers(5, 3); // Calling the function and storing the result echo $result; // Outputs: 8
In this example, the addNumbers function performs the addition of two numbers and returns the result using the return statement. When the function is called with addNumbers(5, 3), the returned value (8) is stored in the $result variable and then displayed.
Functions that return values are valuable when you want to encapsulate a task and obtain a result that can be used elsewhere in your code. They are commonly used for calculations, data retrieval, and various other operations in PHP.