Home  >  Article  >  Backend Development  >  php递归函数return会出现无法正确返回想要值的情况

php递归函数return会出现无法正确返回想要值的情况

PHP中文网
PHP中文网Original
2017-03-15 15:42:591680browse

php递归函数中使用return的时候会碰到无法正确返回想要的值得情况,如果不明白其中的原因,很难找出错误的,就下面的具体例子来说明一下吧:

function test($i){
    $i-=4;
    if($i<3){
        return $i;
    }else{
        test($i);
    }
}
echo test(30);

这段代码看起来没有问题,如果不运行一下估计你也不会认为他有什么问题,及时运行起来发现有问题你也不一定知道哪里有问题,但其实这个函数的else里面是有问题的。在这段代码里面执行的结果是没有返回值的。

所以虽然满足条件 $i<3 时return $i整个函数还是不会返回值的。因此对上面的PHP递归函数可做如下修改:

function test($i){
    $i-=4;
    if($i<3){
        return $i;
    }else{
        return test($i);//增加return,让函数返回值
    }
}
echo test(30);

相关文章
php递归函数怎么用才有效?php递归函数典型例子
php递归函数 PHP中Array相关函数简介
浅析PHP递归函数返回值的使用

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn