Home >Backend Development >PHP Tutorial > 怎么限制递归函数的次数

怎么限制递归函数的次数

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-13 12:59:202040browse

如何限制递归函数的次数?

function add($a){

    if ($a 
        $a = $a +2;

        echo $a.",";

        $a = add($a);

    }

    return $a;

}

add(15);

?>

这个函数会罗列出从$a开始到99的单数,但是我只想调出一个10个数字?那我要如何限制递归函数的次数?(这个只是我一个函数的简化的例子,所以请从「如何限制递归函数次数」的方向作解答。谢谢。

输出结果应该是「17,19,21,23,25,27,29,31,33,35」
------解决方案--------------------
既然有次数限制,那就要传递限制数了

function add($a, $n=false){ //默认不限制次数<br />
  if($n !== false && $n == 0) {<br />
    return;<br />
  }else {<br />
    $n--;<br />
  }<br />
  if ($a < 99) {<br />
    $a = $a +2;<br />
    echo $a.",";<br />
    $a = add($a, $n);<br />
  }<br />
  return $a;<br />
}<br />
<br />
add(15, 10);
17,19,21,23,25,27,29,31,33,35,

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