Home  >  Article  >  Backend Development  >  这个递归是如何运算的

这个递归是如何运算的

WBOY
WBOYOriginal
2016-06-06 20:32:41919browse

<code><?php $string = 'abc';
reverse($string);
function reverse($str){
    if(strlen($str)>0){
        reverse(substr($str,1));
    }
    echo substr($str,0,1);
    return;
}
?>
</code>

这是将abc顺序颠倒显示cba的递归函数。函数执行时每一步是怎样执行的才得到最后颠倒的顺序。请分解一下执行步骤,谢谢

回复内容:

<code><?php $string = 'abc';
reverse($string);
function reverse($str){
    if(strlen($str)>0){
        reverse(substr($str,1));
    }
    echo substr($str,0,1);
    return;
}
?>
</code>

这是将abc顺序颠倒显示cba的递归函数。函数执行时每一步是怎样执行的才得到最后颠倒的顺序。请分解一下执行步骤,谢谢

<code>php</code><code>$string = 'abc';
reverse($string);
function reverse($str){
    if(strlen($str)>0){
        reverse(substr($str,1));
    }
    echo substr($str,0,1);//用var_dump(substr($str,0,1));看
    return;
}
第一次调用reverse(abc) if成立 
再二次调用reverse(bc) if成立
再三次调用reverse(c) if成立
再四次调用reverse('') if不成立
然后往回调,依次输出false,c,b,a
其实可以implode('',array_reverse(str_split('abc')));//cba
</code>
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