Returning values
Learn to return a value from a function and use it at the call site.
Returning values
The return statement sends a value out of the function. For example, after function pi() { return 3.14; }, writing $x = pi(); makes $x equal to 3.14.
When return runs, the function ends; the code after it does not run. You can print the returned value with echo, assign it to a variable or use it inside an expression.
Early return and void functions
A function can run without return; in that case it returns null. Such functions are called void functions; they are usually used for side effects, for example printing or writing to a file.
You can end a function early by using return inside a condition. For example, if ($error) { return; } exits the function as soon as an error is seen.
Exercise Return a circle area
Define a parameterless function named getCircleArea. In the body, write return 3.14 * 2 * 2; (assume radius 2). Then print the result with echo getCircleArea() . "\n";.
Show example solution
Write function getCircleArea() { return 3.14 * 2 * 2; }, then print with echo getCircleArea() . "\n";.
Example solution:
<?php
// Define getCircleArea and print its result
function getCircleArea() {
return 3.14 * 2 * 2;
}
echo getCircleArea() . "\n";
Test yourself
-
Match return and echo
- return 5;
- Returns a value
- echo 5;
- Prints to screen
- return;
- Returns null
-
Complete the return statement
function answer() { ____ 42; } echo answer();Show answer
function answer() { return 42; } echo answer(); -
What is the output of the code below?
function magic() { return 7; echo "After"; } echo magic();- Only 7
- 7After
- After7
- Nothing
Show answer
Only 7 — Correct. return gives the value and exits the function; the rest does not run.