PHP递归函数

PHP递归函数 首页 / PHP入门教程 / PHP递归函数

PHP还支持递归函数调用,例如C/C++。在这种情况下,无涯教程在函数内调用当前函数,也称为递归。

建议避免递归函数调用超过200个递归级别,因为它可能会破坏堆栈并可能导致脚本终止。

示例1:打印编号

function display($number) {  
    if($number<=5){  
     echo "$number";  
     display($number+1);  
    }
}  
  
display(1);  
?>  

输出:

链接:https://www.learnfk.comhttps://www.learnfk.com/php/php-recursive-function.html

来源:LearnFk无涯教程网

1
2
3
4
5

示例2:阶乘数

function factorial($n)  
{  
    if ($n < 0)  
        return-1;/*Wrong value*/ 
    if ($n == 0)  
        return 1;/*Terminating condition*/ 
    return ($n * factorial ($n-1));  
}  
  
echo factorial(5);  

输出:

链接:https://www.learnfk.comhttps://www.learnfk.com/php/php-recursive-function.html

来源:LearnFk无涯教程网

120

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

AI 音视频创作入门课 -〔唐子轩〕

Midjourney入门实践课 -〔Jovi〕

给程序员的写作课 -〔高磊〕

大厂设计进阶实战课 -〔小乔〕

说透数字化转型 -〔付晓岩〕

分布式系统案例课 -〔杨波〕

接口测试入门课 -〔陈磊〕

人人都能学会的编程入门课 -〔胡光〕

从0开始学大数据 -〔李智慧〕

好记忆不如烂笔头。留下您的足迹吧 :)