php - Function returns strings but not when stored in variable

964

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;
        }
    }
}
874

Answer

Solution:

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 :-)

People are also looking for solutions to the problem: php - Retrieve 'id' from an URL using regular expression

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.