Forum Moderators: coopster

Message Too Old, No Replies

How to check if the function call is first or not in recursive functio

         

PHPycho

8:03 am on Dec 31, 2009 (gmt 0)

10+ Year Member



Suppose i have following recursive function(dummy):
[PHP]function someRecursiceFunc($id){
if(/*check_if_call_is_first*/){
//want to do some operations here with the $id
}
$sql = "SELECT id, parent_id, title FROM some_table WHERE id = ".(int)$id;
$db_result = mysql_query($sql);
while($row = mysql_fetch_array($db_result)){
someRecursiveFunc($row['parent_id']);
}
}[/PHP]

i tried with the static $count = 0 & incremented in while() loop
but this caused problem in function call inside loop(as static variable preserves the value)
For example:
[PHP]foreach($datas as $data){
someRecursiveFunc($data['id']);//value of $count went increasing
}[/PHP]

is there any techinque so that i can check for first call?

coopster

2:59 pm on Dec 31, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



static [php.net] looks like an obvious solution to your issue. Perhaps check it's value to see if the static variable has changed from zero and if so, don't do your initialization processing.

Psychopsia

10:53 pm on Dec 31, 2009 (gmt 0)

10+ Year Member



Hello!
For my coding I use:

function someRecursive()
{
static $first;

if (!isset($first))
{
//code
$first = 1;
}
// more code
}

Hope this helps :)