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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.