A nice conclusion for the first tutorial of this series consists of defining a pair of recursive functions that can be used in real PHP applications. The first example shows a recursive version of the PHP built-in “array_map()” function, which not surprisingly can be applied to recursive arrays, in order to escape conflictive characters. Here is the source code for the “escapeArray()” function: function escapeArray($inputData){ Despite the fact that the code for the above function is really compact, its functionality is actually worth noting. In short, all this function does is apply the “mysql_escape_string()” PHP built-in function to all the elements of a specific recursive array. This can be pretty useful in situations where a sequence of array values must be escaped before being stored in a database table. Now, have a look at the following snippet of code, which shows how to use the above function: // define recursive array As you can see, after defining a recursive $data array, I used “escapeArray()” as the callback function for the PHP built-in “array_map()” function, in order to escape all the corresponding array elements. The respective output of this script is the following: Array ( [0] => I'm Alejandro Gervasio [1] => Array ( [0] => Take As illustrated above, each element of the sample array has been appropriately escaped by adding the typical leading slash to all the single quotes. Finally, the same “escapeArray()” function can be modified, in order to apply character escaping only when “magic_quotes” are disabled. Have a look at the improved version of this function: function escapeArray($inputData){ In this case, the function remains nearly the same, except for the checking block that returns the escaped array elements only when the value for “magic_quotes” is turned off. Isn’t recursion a cool concept? You bet. Final thoughts In this first article I provided you with the basics of recursion in PHP. Through several, easy-to-grasp hands-on examples you learned how to define and use recursive functions, which can be handy for solving certain programming issues, instead of using conventional iteration. However, this is merely the beginning of the journey. Over the next part of the series, I’ll demonstrate how to use recursion in some real object-oriented PHP applications. See you then!
blog comments powered by Disqus |