Here is your code annotated:
function test($a, $b){
$arr = [$a, $b];
if($a == 1){
echo "first here";
test(3,4); // Return value from recursive call discarded
}
else{
echo "second here";
return [$a, $b]; // if $a != 1, will return here
}
echo "should have returned earlier";
return $arr; // if $a == 1, will always return here
}
If you follow all the possible paths through, you'll see that the function always returns [$a, $b] since the return value from test(3,4) is immediately discarded, and the function continues.
The change that is needed to get the output you are expecting is:
- test(3,4);
+ return test(3,4);
At this point, you don't need the final two lines, since both branches of the if are returning:
- echo "should have returned earlier";
- return $arr;
Now $arr is not used, so it can be removed too:
- $arr = [$a, $b];
-
This gives:
function test($a, $b) {
if ($a == 1) {
echo "first here";
return test(3, 4);
}
else {
echo "second here";
return [$a, $b];
}
}
However, some people don't like multiple returns / early returns. You can use the following code instead:
function test($a, $b) {
if ($a == 1) {
echo "first here";
$arr = test(3, 4);
}
else {
echo "second here";
$arr = [$a, $b];
}
return $arr;
}
Consider adding extra spaces like I have done for readability. If your function should only work with integers consider === instead of ==. I also recommend using a good unit test framework with code coverage. That way you can see which lines were executed (but not in which order) which would help you to find, understand and fix bugs.