PHP
  Home arrow PHP arrow Page 2 - Fundamentals of Recursion in PHP
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Fundamentals of Recursion in PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 14
    2006-05-01


    Table of Contents:
  • Fundamentals of Recursion in PHP
  • Introducing the basics of recursion: developing an easy-to-grasp example
  • Emphasizing the fundamentals of recursion: defining an improved recursive function
  • Recursion in a more helpful sense: defining two handy recursive functions

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Fundamentals of Recursion in PHP - Introducing the basics of recursion: developing an easy-to-grasp example
    ( Page 2 of 4 )

    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
     

       

    PHP ARTICLES

    - Using Directory Iterators to Build Loader Ap...
    - Using the spl_autoload() Functions to Build ...
    - Working Out of the Object Context to Build L...
    - Using the _autoload() Magic Function to Buil...
    - The Destruct Magic Function in PHP 5
    - The Autoload Magic Function in PHP 5
    - Developing a Recursive Loading Class for Loa...
    - The Sleep and Wakeup Magic Functions in PHP 5
    - Using the Clone Magic Function in PHP 5
    - Including Files Recursively with Loader Appl...
    - The Call Magic Function in PHP 5
    - Designing a Captcha System with PHP and MySQL
    - Using Static Methods to Build Loader Apps in...
    - The Isset and Unset Magic Functions in PHP 5
    - Advanced PHP Form Input Validation to Check ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway
    Stay green...Green IT