As I said before, recursion is a topic that is best understood by example. Keeping in mind this idea, below I coded a new version of the “arrayToFile()” function that you learned before, which is slightly more understandable. Please have a look at its respective signature: function dataToFile($inputData,$file){ In this case, I wrote down this new recursive “dataToFile()” function, which is also handy for saving the contents of a recursive array to a specific text file. As you can appreciate, the function is a bit more compact and readable because I restructured its source code, in order to check whether a given input element is an array, and process it accordingly. In the two recursive functions defined earlier (including the one you saw in the previous section), program control is implicitly returned to the main program by the lines that save the data to the sample file: if(!$fp=fopen($file,'a+')){ After defining the above “dataToFile()” recursive function, it’s possible to set up an example that shows how to use it. Here is a simple implementation of this function: // define recursive array Indeed, the above example is extremely easy to grasp. Basically what I did was build up a new recursive array and use the “dataToFile()” function to save the array elements to file, which is very similar to the example you learned in the previous section. As a result of running the previous script, below you can see how all the elements of the $data array are saved to the “data_file.txt” file: A B This is an example of recursion This is another example of recursion That was pretty cool, since the “dataToFile()” function is capable of traversing a specific recursive array and storing the corresponding elements in a given text file. Now, do you see that defining a recursive function in PHP is not so difficult as it seems? I hope you do. At this point, I coded some PHP functions that come handy for demonstrating how to use recursion in PHP. However, I’m not done yet. In the next section, I’ll write a couple of recursive functions that can be a little more helpful when they are included in real PHP applications. Thus, keep on reading to learn how this is achieved.
blog comments powered by Disqus |