1

In this function that I use to search some element in a tree ,how can I stop the recursion when I found the seached element?

public function find($element, $found_path){
    var_dump($element->getName());
    if($element->getAbsolute_path() == $found_path){
        $this->current = &$element;
    } else {
        if(isset($element->descendants)){
            foreach($element->descendants as $descendant){
                $this->find($descendant, $found_path);
            }
        }
    }                   
}

The search is correct, but the complete tree is visited. I need to stop when the searched element is found.

Dycey
  • 4,767
  • 5
  • 47
  • 86
af_787
  • 11
  • 1
  • set a flag and then check it in the function every time. – ADyson Jun 05 '20 at 08:25
  • 2
    Use the return keyword to leave the function. – Markus Zeller Jun 05 '20 at 08:27
  • @MarkusZeller I used `return $element;` instead of `$this->current = &$element;` but the recursion continues – af_787 Jun 05 '20 at 08:44
  • It would be better to use the returned value of the function for both the result and the recursion stop, with updating a variable there is always the risk it is overwritten by a concurrent fonction execution – Kaddath Jun 05 '20 at 08:45
  • 1
    Does this answer your question? [PHP: Returning from a recursive array searching function](https://stackoverflow.com/questions/37280124/php-returning-from-a-recursive-array-searching-function) – Kaddath Jun 05 '20 at 08:59
  • Does this answer your question? [How can I break a loop which has a condition in it? (PHP)](https://stackoverflow.com/questions/17475470/how-can-i-break-a-loop-which-has-a-condition-in-it-php) – Vendetta Jun 05 '20 at 09:23

1 Answers1

0

You can use either the return or break function to escape a loop. For example:

public function find($element, $found_path){
    var_dump($element->getName());
    if($element->getAbsolute_path() == $found_path){
        $this->current = &$element;
    } else {
        if(isset($element->descendants)){
            foreach($element->descendants as $descendant){
                $this->find($descendant, $found_path);
                return;
            }
        }
    }                   
}

Break Documentation

Return Documentation

Vendetta
  • 2,078
  • 3
  • 13
  • 31