Jump to content

Recursive function


crashmaster

Recommended Posts

Hi there,

I have function, which gets $path to file, if file doesnt exist, it goes 1 level up...

But this function doesnt work. why ??

 

function _path ($path) {

    if (!file_exists($path)) {
        _path('../'.$path);
    } else {
        return $path;
    }

}

Link to comment
https://forums.phpfreaks.com/topic/96603-recursive-function/
Share on other sites

You are doing the recursion wrong. For recursion to work, it has to return the return value of the internal call. Your functions are working, but the return value is getting returned to the first call and nothing is done with it. Add the word return to your code and it should work fine:

function _path ($path) {

    if (!file_exists($path)) {
        return _path('../'.$path);
    } else {
        return $path;
    }

}

Link to comment
https://forums.phpfreaks.com/topic/96603-recursive-function/#findComment-494357
Share on other sites

Forgot a return there...

 

<?php

function _path ($path) {

    if (!file_exists($path)) {
         return _path('../'.$path);
    } else {
        return $path;
    }

}
?>

 

 

Keep in mind that this function (theoretically) will never stop if there's no such file name in the current folder and all the folders above it. You should add a limit.

Example: (No need to change anything in the function call, $call is an optional parameter)

 

<?php

function _path ($path, $calls = 0) {

    $calls ++;
    if($calls > 15)
         return FALSE;
    if (!file_exists($path)) {
         return _path('../'.$path, $calls);
    } else {
        return $path;
    }

}
?>

 

 

Orio.

Link to comment
https://forums.phpfreaks.com/topic/96603-recursive-function/#findComment-494365
Share on other sites

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.