Recursion in PHP

Learn about recursion in PHP and optimization techniques for recursive codes.

We’ve already discussed composition, functors, monads, and task parallelization. This chapter’s contents includes ideas used either in direct conjunction with said topics or concepts that accentuate their importance. Recursion, pattern-matching, and property-testing ensure that iterations are cleaner, flow-control is more concise, and quality assurance for functional programming apps is tractable, respectively.

Definition of recursion

Recursion is a pattern that features functions calling themselves. It is, in terms of effect, very similar to iteration through control structures (if/else, do-while, and the like), but has some unique fundamental preconditions for success. Among these conditions are:

  • A base case: The condition that causes the termination of recursion.

  • Varied cases: Division of the problem into sub-problems.

  • No cycles: An absence of repeat calls to a specific sub-problem in the same recursive sequence.

Example 1: Fibonacci series

Take the Fibonacci series recursive function, for instance. It automatically evaluates to the value supplied to it if the said value is less than two (a base case). It repeatedly computes, through multiple steps specified in the recursive calls, fib($n - 1) and fib($n - 2), the nth Fibonacci number.

Get hands-on with 1400+ tech skills courses.