php遞歸,兩個例子讓你掌握PHP遞歸

認真理解下面兩個例子,就能夠掌握PHP遞歸了code

function test($n){
    if($n>0){
        echo 'a'.$n."\n";
        $n = test($n-1);
    }else{
        echo 'b'.$n."\n";
        return $n;
    }
    echo 'c'.$n."\n";
    return $n;
}
echo test(2);exit;

返回結果:
a2
a1
b0
c0
c0
0
華麗分割線--------------------------------遞歸

function test($n){
    if($n>0){
        echo 'a'.$n."\n";
        test($n-1);
    }else{
        echo 'b'.$n."\n";
        return $n;
    }
    echo 'c'.$n."\n";
    return $n;
}
echo test(2);exit;

返回結果:
a2
a1
b0
c1
c2
2it

相關文章
相關標籤/搜索