Jump to content

can you make a function repeat?


php_joe

Recommended Posts

There's a way to prevent that though, right? so that the code stops parsing when the page is closed?

 

When using recursion you must always define a (set of) base case(s).  Defining attainable base cases ensure that your program will terminate.  To illistrate this, consider a recursively defined power function, we'll call it rpow().  To begin we must know something about abour problem; in this case, that x to the 0th power is 1 and that x to kth power is x^(k-1) * x (remember your algebra? ;)) or rpow(x, k-1) * x.  With this information we can construct a recursive solution.

 

<?php
rpow($x, $k){
  // Our base case is x^0 = 1.  We know that this case will always be reached, 
  // provided that k is an integer greater than -1 because in our recursive step 
  // below we are always subtracting 1 from k, it follows that k will eventually be 0.
  if($x == 0){
    return 1;
  }
  // If k != 0 then, by the definition we provided (x^(k-1) * k) we will recurse (call "ourself)
  return rpow($x, $k - 1) * $x;
}
?>

 

Recursion provides an elegant solution to many problems, however, as the previous posters have said  we would need to know more about the problem you are trying to solve in order to help you along with a solution.

 

Best,

 

Patrick

You can do what thorpe said:

 

<?php

function foo() {
  if($handle = fopen($url)){
    fwrite($handle, $info);
    fclose($handle);
  } else {
    foo();
  }
}

foo();

?>

 

but u can add a couple lines of code.

 

<?php
$i = 0;
function foo() {
if($i == 5) {
  if($handle = fopen($url)){
    fwrite($handle, $info);
    fclose($handle);
    $i++;
  } 
  }
  else {
    foo();
    $i++;
  }
}

foo();

?>

I think we might need a bit more information about what you're trying to achieve in order to help you with your function.

 

Nothing specific at the moment, but I've occationally run into a situation that I'd want to repeat, maybe with a slightly altered set of circumstances.

 

If you had a situation where the function was in an endless loop (like, you'd set the timeout at 0) would it continue to loop if the visitor closed the webpage?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.