Home arrow PHP arrow Page 2 - Fundamentals of Recursion in PHP

Introducing the basics of recursion: developing an easy-to-grasp example - PHP

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.

TABLE OF CONTENTS:
  1. Fundamentals of Recursion in PHP
  2. Introducing the basics of recursion: developing an easy-to-grasp example
  3. Emphasizing the fundamentals of recursion: defining an improved recursive function
  4. Recursion in a more helpful sense: defining two handy recursive functions
By: Alejandro Gervasio
Rating: starstarstarstarstar / 23
May 01, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

To start illustrating the basic concepts of recursion in PHP, first I’ll show you some friendly examples of recursive functions. In this way you can acquire a solid knowledge of the topic. Please study the first example listed below, which uses a recursive function to deeply traverse an array structure and save its elements to a sample text file:

// recursive function to traverse arrays and save elements to
file
function arrayToFile($inputArray,$file){
    foreach($inputArray as $element){
        if(is_array($element)){
            // call recursively the 'arrayToFile()' function
            arrayToFile($element,$file);
        }
        else{
            if(!$fp=fopen($file,'a+')){
                trigger_error('Error opening data
file',E_USER_ERROR);
            }
            fwrite($fp,$element."n");
            fclose($fp);
        }
    }
}

In the above example, you can see that I defined the recursive “arrayToFile()” function, which is tasked with taking up an incoming recursive “$inputArray” array and storing each of its elements in the “$file” text file. Although its definition is rather trivial, this function helps you see in a nutshell how recursion works. Notice how the function calls itself, in order to navigate the respective input array and save all its elements to the specified file.

Here, there are some important points to consider regarding this example, and of course, the subsequent ones: first, each time the function calls itself, it makes a copy of its source code in the server. This means that different instances of the function will be maintained in memory, preventing the PHP interpreter from being confused about what instance to handle.

Secondly, when each function call has finished saving an array element to file, program control is returned to the instance that called the function, until finally control is moved back to the main routine. In accordance with these concepts, it’s clear to see that a recursive function is much more resource consuming than traditional iteration, since it needs to make copies of itself in memory.

Finally, even when recursion can be used as a more professional approach for solving specific programming problems, its drawbacks reside mainly on the potential overhead of multiple function calls, and the difficulty many programmers have in coding an ending condition for the recursive process. This leads very often to making a function recur indefinitely, until the timeout for the script is reached, or eventually until the server runs out of resources (specifically RAM memory).

Having explained in detail the particulars of how recursion works internally, it’s time to show how to use the “arrayToFile()” function that I defined above. Here is a brief example that demonstrates the capacity of this simple recursive function:

// define recursive array
$data=array('element1'=>1,'element2'=>2,'element3'=>array
('recursive_element1'=>3,'recursive_element2'=>4,
'recursive_element3'=>array('key1'=>'This is an example of
recursion','key2'=>'This is another example of
recursion')),'element4'=>4);
// save array elements to file
arrayToFile($data,'data_file.txt');

As shown above, I first defined a recursive array, that is, some elements are also arrays, and next passed it as an argument to the “arrayToFile()” function, in order to store each element in a sample “data_file.txt” text file.

The contents of this file, after running the above script, are listed below:

1

2

3

4

This is an example of recursion

This is another example of recursion

4

As you can see, the function has gone deeply through the $data recursive array and stored the corresponding elements in the sample text file. Hopefully, this basic example should give you a pretty clear idea of how a recursive function can be defined in PHP. Nevertheless, recursion is best understood by thorough practice. That’s precisely what I’ll try to provide you in the next few lines, thus please click on the link below to see more examples of how to write recursive functions in PHP.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: