Jump to content

count in function recursion


MDanz

Recommended Posts

You can use a static variable.  Static variables retain their values each time you call a function.  It's sort of like a global variable but within the function's scope.  (You can of course also just use a global variable, but this keeps it with the function scope).

 

Normal:

function blah () {
  $x++;
  echo $x;
}

for ($y = 0;$y<10;$y++) {
  blah();
}

// output: 1111111111

 

Static

function blah () {
  static $x;
  $x++;
  echo $x;
}

for ($y = 0;$y<10;$y++) {
  blah();
}

// output: 12345678910

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.