php遞歸注意事項

/* 循環去除字符串左邊的0 */
function removeLeftZero($str){
    if($str['0'] == '0'){
        $str = substr($str, '1');
        removeLeftZero($str);
    }else{
        return $str;
    }
}

這樣運行之後若是是遞歸是不會有返回值的,遞歸後即便知足else條件也不會有返回值,應該改成函數

/* 循環去除字符串左邊的0 */
function removeLeftZero($str){
    if($str['0'] == '0'){
        $str = substr($str, '1');
        return removeLeftZero($str);
    }else{
        return $str;
    }
}

也就是說在要遞歸的函數內部的函數前面要加return spa

相關文章
相關標籤/搜索