1

I have a strange problem with a function i wrote. When returning an hardcoded string like "Hello" it returns this value, but when i store this value in a variable it doesn't return anything.

Also when i don't store it in a variable and try to return it nothing gets returned.

Below is my code. Can anybody see what i'm doing wrong?

Thanks in advance.

 public function getPath($pageID = null) {
    if($pageID == null) $pageID = $this->id;

    $data = $this->_db->fetch_array("SELECT * FROM `pages` WHERE `id` = '".$pageID."'");

    if(!empty($data)) {
        $this->tempPath[] = $data['basename'];

        if($data['parentID'] != 0) {
            $this->getPath($data['parentID']);
        } else {
            $returnPath = $this->tempPath;
            $this->tempPath = array();
            $returnPath = implode('/', array_reverse($returnPath));
            //This variable holds the value, when echo'ed its the correct value
            echo $returnPath;

            return $returnPath;
        }
    }
}
6
  • Can't reproduce your problem. Do you get any errors? Do you show us your real code? Commented Oct 18, 2015 at 10:24
  • This is all the code used in the function, it's producing the correct data but when returning nothing gets returned. When i code: return "Hello" it does return "Hello", But it doesn't return any values in variables. Commented Oct 18, 2015 at 10:25
  • What is the exact output of: var_dump($returnPath); right before the return statement? Commented Oct 18, 2015 at 10:28
  • This is the ouput: string(15) "admin/dashboard" string(15) "admin/pages/add" string(11) "admin/pages" Commented Oct 18, 2015 at 10:30
  • 1
    Is this code in a loop which you don't show us?! Commented Oct 18, 2015 at 10:42

1 Answer 1

1

Rewrote the code to the following and now it's working

 public function getPath($pageID = null) {
    if($pageID == null) $pageID = $this->id;

    $data = $this->_db->fetch_array("SELECT * FROM `pages` WHERE `id` = '".$pageID."'");

    if(!empty($data)) {
        $this->tempPath[] = $data['basename'];
    }

    return implode('/', $this->tempPath);
}

Problem was that the code was in a foreach loop which kept overwriting the correct values and looping till there is no path to return. Thanks for the suggestions.

More code isn't always better :-)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.