Function within a function

Discussion in 'PHP' started by Cinta April, Apr 17, 2008.

  1. #1
    Hi I am trying to use a function within a function. Is there an example of a function using itself within the definition of the function? When I try my current version it says the function is not defined.
     
    Cinta April, Apr 17, 2008 IP
  2. Louis11

    Louis11 Active Member

    Messages:
    783
    Likes Received:
    26
    Best Answers:
    0
    Trophy Points:
    70
    #2
    Yes, it's called recursion. Here is a little something that I whipped up for you to have a look at:
    
    	function divide($number){
    		if($number < 1)
    			exit("Done: " . $number);
    			
    		divide($number/2);
    	}
    	
    	divide(100);
    
    PHP:
    Nothing special, but you get the idea ;)

    On a side note, recursion is a terrible way of doing something. If you can, avoid it as it is a memory hog and has a longer run time than an inline function. But, I will admit, in some cases it is warranted and can give you much more concise code.
     
    Louis11, Apr 17, 2008 IP