Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

counting the number of times a recursive function is called

Tags:

function

php

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?

like image 679
Source Avatar asked Nov 28 '22 08:11

Source


2 Answers

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;
like image 163
deceze Avatar answered Nov 30 '22 23:11

deceze


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.

like image 31
Mladen B. Avatar answered Nov 30 '22 21:11

Mladen B.