Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 12 / 68

Recursive Functions

In this lesson you will learn how to write a recursive function in PHP and understand the basic idea of a function that calls itself. This is for anyone searching for "PHP recursive function how to use".

A recursive function is a function that calls itself. It suits work that repeats the same calculation pattern, such as "n! = n x (n-1)!". Always provide a stopping condition, or the function will call itself forever and the program will crash.

The sample code has factorial keep calling itself in the form $n * factorial($n - 1) until it reaches the stopping condition $n <= 1. Writing out the steps of computing the factorial of 5 by hand really helps it click.

A common stumbling block for beginners is forgetting that stopping condition and recursing forever. Deep recursion also consumes a lot of stack, so it is worth considering whether a loop would do instead. How deep is safe varies by environment.

In real-world development, recursion is a natural fit for hierarchical data such as folder trees or nested comment replies. Understand the mechanism once and you will find it applies widely.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)