PHP遞迴函式
阿新 • • 發佈:2019-02-09
遞迴函式:自己呼叫自己
使用引用獲得遞迴結果:
function showColors($colors,&$colorStr) { if(count($colors)==0)return false; $color = array_pop($colors); $colorStr .= showColors($colors,$colorStr); return " color:".$color; } $colors = ['red','blue','purple','green','yellow']; $colorStr = ""; showColors($colors,$colorStr); echo $colorStr;
使用靜態變數實現遞迴
function showColors($colors) { static $colorStr = ''; if (count($colors) == 0) return false; $colorStr .= " color:".array_pop($colors); showColors($colors); return $colorStr; } $colors = ['red', 'blue', 'purple', 'green', 'yellow']; echo showColors($colors); //color:yellow color:green color:purple color:blue color:red function test(){ static $i=0; if($i++<10){ echo $i; test(); } } test();//12345678910