Techniques for Working with Return in PHP
There are some techniques for working with return
that simplify the code.
Consider, for example, the following code:
<?php
function func($num) {
if ($num >= 0) {
$res = sqrt($num);
} else {
$res = 0;
}
return $res;
}
echo func(3);
?>
As you can see, in this code, depending
on the condition, either one or another value will be
assigned to the variable $res
.
And the last line of the function returns the contents of this
variable via return
.
Let's rewrite this code in a more shortened
form, getting rid of the unnecessary variable
$res
:
<?php
function func($num) {
if ($num >= 0) {
return sqrt($num);
} else {
return 0;
}
}
echo func(3);
?>
Given the following function:
<?php
function func($num1, $num2) {
if ($num1 > 0 and $num2 > 0) {
$res = $num1 * $num2;
} else {
$res = $num1 - $num2;
}
return $res;
}
echo func(3, 4);
?>
Rewrite it in a shortened form according to the studied theory.