NamePros
Welcome, Guest! Ready to make a name for yourself in the domain business? We welcome both the hobbyist and professional domainer to join the discussion as part of the NamePros community.

Click here to create your profile to start earning reputation for posting, and trader ratings for buying & selling in our free e-marketplace. Build your trader rating with each successful sale. Our system has tracked over 100,000 sales and counting!
FAQ & TOS Register Search Today's Posts Mark Forums Read

Go Back   NamePros.com > Website Development Discussion Forums > Programming > CODE
Reload this Page Working with recursive functions within php

CODE This forum is for posting code snippets and example scripts that aren't quite tutorials, but could be useful for others. You may post code snippets and/or completed scripts that you've written and want to share here.

Advanced Search
7 members in live chat ~  


Closed Thread
 
LinkBack Thread Tools
Old 08-17-2007, 05:31 PM THREAD STARTER               #1 (permalink)
NamePros Expert
 
Peter's Avatar
Join Date: Nov 2003
Location: Scotland
Posts: 5,074
Peter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond repute
 


Child Abuse Save The Children Save The Children Help The Homeless - Holiday 2009 Help The Homeless - Holiday 2009 Help The Homeless - Holiday 2009 Help The Homeless - Holiday 2009

Working with recursive functions within php


1 thing within PHP that some people have trouble with is recursive functions.

In case you are not sure what a recursive function is, a recursive function is a function that performs a task and may have to call itself to perform the same task again. Hopefully the following tutorial will enlighten you somewhat.

You maybe wondering why a recursive function might be necessary. The simple answer is that without recursive functions you are set to rely on nested if else statements which can get very messy. Also if you have nested if else statements you need to know how deep you need to go, a recursive function can effectively continuously go on (well until the server runs out of memory anyway)

You may have noticed that magic_quotes_gpc has received a lot of flack in the last couple of years. I am not going to go into why this is but what I will say is that magic_quotes_gpc attempts to make safe any input that is gained from form methods such as GET and POST it also does the same for COOKIE data (hence why it has gpc at the end of it's name).

The function we are going to create will check that this is enabled and make the arrays safe.

Firstly let me show you the whole code then I will explain it a bit at a time:-

PHP Code:
function clean_array($array)
{
    
$temp = array();
    if (
is_array($array))
    {
        foreach (
$array as $key=>$value)
        {
            if (
is_array($value))
            {
                
$temp[$key] = clean_array($value);
            }
            else 
            {
                if (
get_magic_quotes_gpc())
                {
                    
$value stripslashes($value);
                }
                
$temp[$key] = $value;
            }
        }
    }
    else 
    {
        if (
ini_get('magic_quotes_gpc') == 1)
        {
            
$array stripslashes($array);
        }
        
$temp $array;
    }
    return 
$temp;

There is nothing too technical within this code snippet but I will go through it regardless.

PHP Code:
function clean_array($array)
{
    
$temp = array(); 
you will most likely know these 2 lines. The first line is simply the definition of the function. In this case the function is called clean_array. As you can see the function requires 1 variable and for the sake of the function it is referred to as $array. The second line simply starts the block of code. Line 3 I have decided to declare a variable as an array. The variable is called $temp and is only available within the function. This is so I can pass the cleaned data to this variable.

PHP Code:
    if (is_array($array))
    {
        foreach (
$array as $key=>$value)
        {
            if (
is_array($value))
            {
                
$temp[$key] = clean_array($value);
            }
            else 
            {
                if (
get_magic_quotes_gpc())
                {
                    
$value stripslashes($value);
                }
                
$temp[$key] = $value;
            }
        }
    } 
Now this is the meat of the function. We start of by ensuring that the input is indeed an array (we will deal with it later if it is not). After this we start a loop to break down the array. We need to keep the key and value for the array as of course you need to know what the data is. Please ignore the next if statement for now and we will come back to that. The else on the other hand contains another if statement that ensures magic_quotes_gpc is enabled (get_magic_quotes_gpc() retrieves the current setting for the option) and for this option 1 indicates that it is enabled. Within this if we simply use stripslashes to remove the slashes that magic_quotes_gpc added. We then input this value into the temp array giving it the same key as it had within the original array.

PHP Code:
    else 
????: NamePros.com http://www.namepros.com/code/363195-working-with-recursive-functions-within-php.html
    {
        if (
get_magic_quotes_gpc())
        {
            
$array stripslashes($array);
        }
        
$temp $array;
    } 
This is the final part of the function. Although it should not happen it is possible that someone may not use the function to check an array so we ensure we are covered in this instance. We do the same here as we did in the else statement earlier.

The final part is the ending of the function:-

PHP Code:
    return $temp;

We simply return the $temp array/variable to the calling script or function to do with it as it will.

Now lets as promised go back the recursive section of the function:-

PHP Code:
if (is_array($value))
            {
                
$temp[$key] = clean_array($value);
            } 
Now what we are doing here is checking to see if the current value within the foreach loop is also an array (as you have probably guessed the built in is_array function as it's name suggests carries out this check). If the value is an array we call our own function assigning the output to the key of this array within the original array. As this function is calling another instance of this function this assignment will receive the output from return $temp; and assign it to the temp array. I know this can get a little confusing lets see it in action.

We can use this function by doing clean_array($array) but as we wish to see the output I will use print_r. The array I will use is:-

$array = array("age"=>"28","name"=>"O\'reilly?", "favorite_bands"=>array('Iron Maiden'=>array("members"=>"Paul Di\'Anno"), 'Dimmu Borgir', "Guns \'N\' Roses"));

As you can see there is a multidimensional array (an array within an array, in fact in this case there is an array within an array within an array). You would of course use this normally with $_POST, $_GET and $_COOKIE.

The output we receive from this is as follows:-

PHP Code:
Array
(
    [
age] => 28
    
[name] => O'reilly?
    [favorite_bands] => Array
        (
            [Iron Maiden] => Array
                (
                    [members] => Paul Di'
Anno
                
)

            [
0] => Dimmu Borgir
            
[1] => Guns 'N' Roses
        
)


As you can see the indexes are 100% intact the only thing that has changed with these is that the slashes have miraculously disappeared.

If you think I have been unclear in this post please feel free to let me know and I will try and correct that.

Points to note.

I do realise that array_map could have been used to do this in a much simpler way however you may not get a full sense of how they work using this function and it may not always be possible.

Although recursive functions can be a very powerful tool you should have caution. As you will probably know an endless loop can cause problems on a server (and if it was not for your maximum execution time with the php configuration it would last forever, or at least until the server was restarted), so can a recursive function that is poorly implemented. If you create a condition in which a recursive function continuously calls itself and the condition to terminate is never met you will suffer a similar problem as an endless loop. Another problem you will have is your servers memory being consumed (or at least the max set by php) by 1 script. This can happen if you have a complex function that is poorly planned out.
????: NamePros.com http://www.namepros.com/showthread.php?t=363195

**ANY CODE I WRITE AND PUBLISH ON NAMEPROS CAN BE CONSIDERED FREE TO USE. IF HOWEVER YOU WISH TO DISTRIBUTE THE CODE EITHER BY ITSELF OR WITHIN AN APPLICATION CREDIT MUST BE GIVEN**
__________________
Manage your portfolio using my new Domain Portfolio Management script.
Securing Your Domain Name From Theft
Last edited by Peter; 08-27-2007 at 11:46 AM.
Peter is offline  
Old 08-27-2007, 10:52 AM   #2 (permalink)
Tech Support
Join Date: Mar 2005
Posts: 4,944
Eric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatness
 

Member of the Month
MOTM September 2005
Save a Life Child Abuse 9/11/01 :: Never Forget Baby Health Marrow Donor Program AIDS/HIV Breast Cancer Animal Rescue Cystic Fibrosis Ethan Allen Fund Animal Cruelty Ethan Allen Fund Ethan Allen Fund Baby Health Cancer Alzheimer's Protect Our Planet Cancer Survivorship SIDS Child Abuse Diabetes Protect Our Planet Multiple Sclerosis Autism Adoption Special Olympics
Nice Peter, although, instead of using:

PHP Code:
if (ini_get('magic_quotes_gpc') == 1)
????: NamePros.com http://www.namepros.com/showthread.php?t=363195
{
    
$array stripslashes($array);

I'd use this instead:

PHP Code:
if (get_magic_quotes_gpc())
{
    
$array stripslashes($array);

Pretty much the same thing, but I'd use the function for getting a specific setting, before using ini_get
Eric is offline  
Old 08-27-2007, 10:59 AM   #3 (permalink)
Traveller
 
-NC-'s Avatar
Join Date: Mar 2007
Location: Yet another city
Posts: 1,419
-NC- has a brilliant future-NC- has a brilliant future-NC- has a brilliant future-NC- has a brilliant future-NC- has a brilliant future-NC- has a brilliant future-NC- has a brilliant future-NC- has a brilliant future-NC- has a brilliant future-NC- has a brilliant future-NC- has a brilliant future
 


Animal Cruelty Animal Rescue Ethan Allen Fund Protect Our Planet
Originally Posted by peter@flexiwebhost
recurring function
more commonly referred to as a recursive function?
__________________
NameCooler.com
-NC- is offline  
Old 08-27-2007, 11:22 AM THREAD STARTER               #4 (permalink)
NamePros Expert
 
Peter's Avatar
Join Date: Nov 2003
Location: Scotland
Posts: 5,074
Peter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond repute
 


Child Abuse Save The Children Save The Children Help The Homeless - Holiday 2009 Help The Homeless - Holiday 2009 Help The Homeless - Holiday 2009 Help The Homeless - Holiday 2009
Originally Posted by -NC-
more commonly referred to as a recursive function?
Hehe yes you are right. I will adapt it now.
__________________
Manage your portfolio using my new Domain Portfolio Management script.
Securing Your Domain Name From Theft
Last edited by Peter; 08-27-2007 at 11:30 AM.
Peter is offline  
Old 08-27-2007, 11:49 AM   #5 (permalink)
Senior Member
 
Barrucadu's Avatar
Join Date: Aug 2005
Location: East Yorkshire, England
Posts: 2,689
Barrucadu is a splendid one to beholdBarrucadu is a splendid one to beholdBarrucadu is a splendid one to beholdBarrucadu is a splendid one to beholdBarrucadu is a splendid one to beholdBarrucadu is a splendid one to beholdBarrucadu is a splendid one to behold
 




I always thought recursive functions didn't work in PHP for some reason, now I know otherwise.
Barrucadu is offline  
Old 08-27-2007, 12:39 PM   #6 (permalink)
Tech Support
Join Date: Mar 2005
Posts: 4,944
Eric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatness
 

Member of the Month
MOTM September 2005
Save a Life Child Abuse 9/11/01 :: Never Forget Baby Health Marrow Donor Program AIDS/HIV Breast Cancer Animal Rescue Cystic Fibrosis Ethan Allen Fund Animal Cruelty Ethan Allen Fund Ethan Allen Fund Baby Health Cancer Alzheimer's Protect Our Planet Cancer Survivorship SIDS Child Abuse Diabetes Protect Our Planet Multiple Sclerosis Autism Adoption Special Olympics
Originally Posted by peter@flexiwebhost
Hehe yes you are right. I will adapt it now.
Fixed the thread title for you as well
Eric is offline  
Old 08-27-2007, 06:54 PM THREAD STARTER               #7 (permalink)
NamePros Expert
 
Peter's Avatar
Join Date: Nov 2003
Location: Scotland
Posts: 5,074
Peter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond repute
 


Child Abuse Save The Children Save The Children Help The Homeless - Holiday 2009 Help The Homeless - Holiday 2009 Help The Homeless - Holiday 2009 Help The Homeless - Holiday 2009
Originally Posted by SecondVersion
Fixed the thread title for you as well

????: NamePros.com http://www.namepros.com/showthread.php?t=363195
Cheers SV noticed it never changed when I made the edits.

Originally Posted by Mikor
I always thought recursive functions didn't work in PHP for some reason, now I know otherwise.
Well they do It can be a very powerful feature but if you do not plan it all correctly it can go horribly wrong and you can get lost trying to pick your way through the logic (i'm sure minds do not work properly recursively, maybe time for an update).
__________________
Manage your portfolio using my new Domain Portfolio Management script.
Securing Your Domain Name From Theft
Peter is offline  
Old 08-28-2007, 06:47 AM   #8 (permalink)
Senior Member
 
Barrucadu's Avatar
Join Date: Aug 2005
Location: East Yorkshire, England
Posts: 2,689
Barrucadu is a splendid one to beholdBarrucadu is a splendid one to beholdBarrucadu is a splendid one to beholdBarrucadu is a splendid one to beholdBarrucadu is a splendid one to beholdBarrucadu is a splendid one to beholdBarrucadu is a splendid one to behold
 




Originally Posted by peter@flexiwebhost
(i'm sure minds do not work properly recursively, maybe time for an update).
Some peoples seem to, below is the mind of a spammer, in PHP form...
PHP Code:
function spam($subject$message$emails){
     
mail(array_rand($emails), $subject$message);
     
spam($subject$message$emails);

Barrucadu is offline  
Old 08-28-2007, 07:04 AM THREAD STARTER               #9 (permalink)
NamePros Expert
 
Peter's Avatar
Join Date: Nov 2003
Location: Scotland
Posts: 5,074
Peter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond reputePeter has a reputation beyond repute
 


Child Abuse Save The Children Save The Children Help The Homeless - Holiday 2009 Help The Homeless - Holiday 2009 Help The Homeless - Holiday 2009 Help The Homeless - Holiday 2009
Originally Posted by Mikor
PHP Code:
function spam($subject$message$emails){
????: NamePros.com http://www.namepros.com/showthread.php?t=363195
     
mail(array_rand($emails), $subject$message);
     
spam($subject$message$emails);

Congratulations your first endless loop using recursive functions
__________________
Manage your portfolio using my new Domain Portfolio Management script.
Securing Your Domain Name From Theft
Last edited by Peter; 08-28-2007 at 07:38 AM.
Peter is offline  
Old 09-05-2007, 04:39 AM   #10 (permalink)
NamePros Regular
 
-PS-'s Avatar
Join Date: Jun 2006
Location: Sydney
Posts: 251
-PS- will become famous soon enough-PS- will become famous soon enough
 



funny, i use recursive functions in one of the pieces of software i wrote

it was decoding emails

bcause you can have multi part attachments - which can be inbeded, can get to be a night mare, but good when used right =)
-PS- is offline  
Closed Thread


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools


 
All times are GMT -7. The time now is 07:08 PM.

Domain name forum recommended by Domaining.com Powered by: vBulletin® Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.6.0 Ad Management plugin by RedTyger