I need to know how many times a recursive function is called within the function. This is my function:
function structure($x) {
$qry = mysql_query("SELECT `parent_id` FROM `categories` WHERE `categories_id`=$x");
$result = mysql_fetch_assoc($qry);
$cat = $result['parent_id'];
if($cat !=0) {
structure($cat);
}
echo $cat.' >';
}
I have tried adding a counter, e.g. $i=0, then $i++, but it will of course revert back to the $i=0 every time the function is called. I have tried adding arrays, and counting the arrays, but of course it has to set a new array, $i=array(), every time the function is called.
The one way I can think might work is if I set the array or counter outside of the function, but I don't know if its possible to call a variable in a function that is outside the function.
Any ideas on how to call a variable outside a function or even a better way to count the times the function is called?
Option 1: pass in a variable by reference
function structure($cat, &$counter) {
$counter++;
...
}
structure('foo', $counter);
echo $counter;
Option 2: use a static
variable
function structure($cat) {
static $counter = 0;
echo ++$counter;
...
}
Option 3: use a global
variable (no no!)
$counter = 0;
function structure($cat) {
global $counter;
$counter++;
...
}
Option 4: use a closure
$counter = 0;
$structure = function ($cat) use (&$counter) {
$counter++;
...
}
$structure('foo');
echo $counter;
You can add another parameter to your recursive function, which will serve as a counter:
function structure($x, $cnt) {
$qry = mysql_query("SELECT `parent_id` FROM `categories` WHERE `categories_id`=$x");
$result = mysql_fetch_assoc($qry);
$cat = $result['parent_id'];
if($cat !=0) {
structure($cat, $cnt++);
}
echo $cat.' >';
}
or you could use a global variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With