Re: Calling functions recursively

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



There are some cases where I see recursive functions as the only option. Picture this function to retrieve data from a global array:

$data = array(array('somedata'=>'somevalue','somedata2'=>'somevalue2'),array('somedata'=>'somevalue','somedata2'=>'somevalue2'),array('somedata'=>'somevalue','somedata2'=>'somevalue2'));
function getdata($key){
return $GLOBALS['data'][$key];
}

But what if some entries in the array should be aliases of others? Using a recursive function, it's simple:

$data = array(array('somedata'=>'somevalue','somedata2'=>'somevalue2'),'ALIAS0',array('somedata'=>'somevalue','somedata2'=>'somevalue2'),array('somedata'=>'somevalue','somedata2'=>'somevalue2'));
function getdata($key){
if(!is_array($GLOBALS['data'][$key])){
preg_match('/^ALIAS([0-9]+)$/',$GLOBALS['data'][$key],$matches);
return getdata($matches[1]);
}else{
return $GLOBALS['data'][$key];
}
}

The array could be fetched inside of the if block, but that would make for longer code, harder to change code, and aliases of aliases would be impossible to have.
Roberto Plomp wrote:

If you mean that it would be more straight forward, hence neater and more
comprehensive and more maintenance and stack friendly to just call the
function in a loop, I agree.

On the other hand ... well, there are arguments for the recursive approach
for a number of algorithms.

Personally I prefer not to use recursive functions, have never really seen
the absolute necessity to do so.

Roberto

----- Original Message -----
From: "Jason Wong" <php-db@gremlins.biz>
Subject: Re: Calling functions recursively



On Saturday 25 January 2003 14:49, Kevin Gordon wrote:

Can functions / methods be called recursively? If so how can this be
done? Comments much appreciated.

google > "php recursive functions"

--
Jason Wong -> Gremlins Associates -> www.gremlins.biz
Open Source Software Systems Integrators
* Web Design & Hosting * Internet & Intranet Applications Development *


/*
QOTD:
"I've just learned about his illness. Let's hope it's nothing
trivial."
*/





--
The above message is encrypted with double rot13 encoding.  Any unauthorized attempt to decrypt it will be prosecuted to the full extent of the law.



[Index of Archives]     [PHP Home]     [PHP Users]     [Postgresql Discussion]     [Kernel Newbies]     [Postgresql]     [Yosemite News]

  Powered by Linux