The Return Statement in PHP
Suppose we have a function that outputs the square of a passed number to the screen:
<?php
function func($num) {
echo $num * $num;
}
func(3); // outputs 9
?>
Suppose we want not to output the value to the screen, but to write it to some variable, like this:
<?php
$res = func(3); // variable $res now contains 9
?>
For this, PHP has a special statement
return
, which allows specifying
the value that the function returns. The
word returns refers to the value
that will be written to the variable if the
called function is assigned to it.
So, let's rewrite our function so that it does not output the result to the screen, but returns it to the variable:
<?php
function func($num) {
return $num * $num;
}
?>
Let's now write the result of the function's work into a variable:
<?php
$res = func(3);
?>
After the data is written to the variable, it can, for example, be output to the screen:
<?php
$res = func(3);
echo $res; // outputs 9
?>
Or you can first modify this data in some way, and then output it to the screen:
<?php
$res = func(3);
$res = $res + 1;
echo $res; // outputs 10
?>
You can immediately perform some actions with the result of the function's work before writing it to a variable:
<?php
$res = func(3) + 1;
echo $res; // outputs 10
?>
You can call our function several times for different numbers:
<?php
$res = func(2) + func(3);
echo $res; // outputs 13
?>
You can not write the result to a variable, but immediately output it to the screen:
<?php
echo func(3); // outputs 9
?>
Create a function that accepts a number as a parameter,
and returns the cube of this number. Using
this function, find the cube of the number 3
and
write it to the variable $res
.
Using the function you created, find
the sum of the cubes of the number 2
and the number 3
and write it to the variable $res
.