Iteration is a straightforward concept. Recursion is a bit more complicated; it can be defined as a regular function that calls itself. PHP supports recursive functions. This article, the first of three parts, will explain recursive functions and help you see why they are useful.
Although you've probably never turned your attention to counting the number of situations where you used iteration during the development of a Web application, writing iterating code is certainly a thing that you’ve done hundreds, not to mention thousands of times.
Iteration is a direct consequence of the ability of computers to automate repetitive tasks, something that has been reflected in most programming languages with the introduction of different iteration structures. In fact, the issue is as simple as it seems: if there’s something that you need to do the same way a number of times inside an application, then you’ll use some kind of loop structure to repeat several blocks of code.
With reference to executing repetitive code, PHP supports the use of the popular “for,” “while,” “do-while” loops and additionally the “foreach” loop, which can be used to easily traverse arrays. Also, there are a few additional built-in functions that perform some sort of iteration on data structures, such as the “array_map()” function, to cite a well-known example. Still, in this article, I'm definitely not going to bore you with an irrelevant list of iterating PHP functions, since you can read the corresponding manual.
In general terms, iteration is a pretty straightforward concept, which as you saw, can be applied in different programming cases with minor hassles. However, let me go one step further in my explanation: say you’ve defined a PHP function that need to be called repetitively within an application, in order to traverse dynamic data structures such as trees or linked lists. In this case, you’re likely to use what is commonly called a “recursive function.”
Essentially, a recursive function can be defined as a regular function that calls itself. Sounds like a confusing concept? It isn't. Fortunately, PHP supports the definition of recursive functions, which can be useful in certain situations. For instance, you'll want to use a recursive function if you’re going to do a lot of work with data trees, which are structured as database tables, or in cases where template files contain nested placeholders and need to be recursively parsed, and so on. You get the idea.
Considering the important role that recursion plays in most programming languages, and specifically in PHP, over this series I’ll be demonstrating how to define and use recursive functions with numerous code samples, thus you can learn quickly how to include them in your own PHP scripts.
Curious about using recursion in PHP? Let’s get started and not waste more time.