Introducing Recursive Functions in PHP

By: Rob Williams

Page 3 of 3

Set for printing

Previous

Using Recursion to Add Flexibility

At this point we've created a nice little function that will handle most arrays effectively. The main limitation at this point though is that it will only work on single-level arrays (1 dimension). To see the problem let's try adding a second dimension to our array and tossing it through our conversion function:

$myArray4 = array();
$myArray4[0] = "jim";
$myArray4[1] = "bob";
$myArray4[2] = "fred";
$myArray4["index1"] = "some value";
$myArray4["index12"] = "index 12 value";
$myArray4["billy"] = NULL;
$myArray4["carlos"] = true;
$myArray4["sandy"] = 12;
$myArray4["petrov"] = false;
//Add the second dimension
$myArray4["2D"] = array();
$myArray4["2D"][0] = "O in the 2D!";
$myArray4["2D"]["blah"] = "blah in the 2D";

//Try calling the existing function
arrayToJS3($myArray4, "myArray4");

As you can see in the output the second dimension gets completely ignored:

myArray4 = new Array();
myArray4[0] = 'jim';
myArray4[1] = 'bob';
myArray4[2] = 'fred';
myArray4['index1'] = 'some value';
myArray4['index12'] = 'index 12 value';
myArray4['billy'] = null;
myArray4['carlos'] = true;
myArray4['sandy'] = 12;
myArray4['petrov'] = false;
myArray4['2D'] = Array;

The problem here is that the value of the entry at index '2D' is actually another array rather than a value that we can directly output. Wait a minute though... what's the purpose of our function? To output all of the values of a given array. Therefore, because the value we've encountered here is an array, we can simply call the function again and pass it the new array.

//Convert a PHP array to a JavaScript one (rev. 4)
function arrayToJS4($array, $baseName) {
   //Write out the initial array definition
   echo ($baseName . " = new Array(); \r\n ");    

   //Reset the array loop pointer
   reset ($array);

   //Use list() and each() to loop over each key/value
   //pair of the array
   while (list($key, $value) = each($array)) {
      if (is_numeric($key)) {
         //A numeric key, so output as usual
         $outKey = "[" . $key . "]";
      } else {
         //A string key, so output as a string
         $outKey = "['" . $key . "']";
      }
      
      if (is_array($value)) {
         //The value is another array, so simply call
         //another instance of this function to handle it
         arrayToJS4($value, $baseName . $outKey);
      } else {


         //Output the key declaration
         echo ($baseName . $outKey . " = ");      

         //Now output the value
         if (is_string($value)) {
            //Output as a string, as we did before       
            echo ("'" . $value . "'; \r\n ");
         } else if ($value === false) {
            //Explicitly output false
            echo ("false; \r\n");
         } else if ($value === NULL) {
            //Explicitly output null
            echo ("null; \r\n");
         } else if ($value === true) {
            //Explicitly output true
            echo ("true; \r\n");
         } else {
            //Output the value directly otherwise
            echo ($value . "; \r\n");
         }
      }
   }
}

Now when we call the function with our two-dimensional array things work perfectly:

//Try calling the revised function
arrayToJS4($myArray4, "myArray4");

And the output:

myArray4 = new Array();
myArray4[0] = 'jim';
myArray4[1] = 'bob';
myArray4[2] = 'fred';
myArray4['index1'] = 'some value';
myArray4['index12'] = 'index 12 value';
myArray4['billy'] = null;
myArray4['carlos'] = true;
myArray4['sandy'] = 12;
myArray4['petrov'] = false;
myArray4['2D'] = new Array();
myArray4['2D'][0] = 'O in the 2D!';
myArray4['2D']['blah'] = 'blah in the 2D';

By making our function recursive we've given it the ability to handle a multi-dimensional array. Although we only built our example array out to two dimensions the function would work just as well with a 12- or 32-dimensional array, all without any need to change or update the code in any way. In order to do this without using recursion we would be required to know the exact dimensions of the array and build multiple functions out accordingly. Thanks to recursion we can pass any array, whether we know its size and dimensions or not, and the output will still work properly.

Conclusion

Recursive functions allow you to reuse the same function any number of times in order to deal with multi-level objects. This adds a whole new level of flexibility to your functions and opens up possibilities that could not even be considered previously. Although our example dealt with converting a PHP array to a JavaScript one, you could easily modify it to convert the array to an XML structure or any number of other purposes. On the other hand, you could also take this technique and use it to create your own XML to PHP array function; once you understand the technique the applications quickly become apparent. Also remember that recursion is a programming concept that exists in most languages. Just because all of our examples were in PHP doesn't mean that you can't take the concept and apply it to other places, for example JavaScript, ASP or any other programming language. As with any concept the most important part is to explore the possibilities!

Page 3 of 3 Previous 1 2 3


download
Download Support Files


Downloads are disabled during your trial period.


Keywords
Recursive function, array, multi-dimensional, JavaScript, generate XML