In PHP, we can achieve specific functions by calling functions. However, sometimes we need to output the execution result of the function to the screen or store it in a variable, which requires the return value of the function.
In PHP, the return value of a function can be realized through the return statement. The return statement is used to terminate the execution of the function and return a specified value or variable.
For example, the following function is used to calculate the sum of two numbers and return the calculation result:
function sum($a, $b) { $result = $a + $b; return $result; }
In the function, we first define a variable $result to store the calculation result , and then use the return statement to return this result.
If we want to output the result of the function, we can do this:
echo sum(2, 3);
This will output the calculation result 5 to the screen.
If we want to store the result of the function into a variable, we can do this:
$total = sum(2, 3); echo $total;
This will store the calculation result 5 in the variable $total and output it to the screen.
In addition to using the echo statement to output function results and store function results in variables, we can also use the return value of the function in other functions or programs. For example:
function multiply($a, $b) { $result = $a * $b; return $result; } function divide($a, $b) { $result = $a / $b; return $result; } $a = 5; $b = 2; $total = multiply($a, $b); $average = divide($total, $a); echo "Total: " . $total . "<br>"; echo "Average: " . $average;
In the above example, we defined two functions multiply and divide, which are used to calculate the product and quotient of two numbers respectively. Then we defined two variables $a and $b, assigning values to 5 and 2 respectively. Then we call the function multiply to calculate the product of $a and $b, and store the calculation result in the variable $total. Then we call the function divide to calculate the quotient of $total and $a, and store the calculation result in the variable $average. Finally, we use the echo statement to output the values of $total and $average.
In short, there are many ways to output the results of a function in PHP, and you can choose the most suitable method according to actual needs. Whether you use the echo statement to output function results, store function results in variables, or use the function's return value in other functions or programs, you need to pay attention to the function's return value type and the correctness of the value to ensure the correctness and accuracy of the program. stability.
The above is the detailed content of How to output function results in PHP. For more information, please follow other related articles on the PHP Chinese website!