Search code examples
phpfunctionrecursionlaravel-5call-by-value

PHP call by value returning less value to the main function


I have a weird issue, i wrote an recursive function to get more results from facebook. In the called function(recursive) i am returning the values to the main function. In the called function when i print the returned value it displays the exact value(generally the array size which is 90). But in the main function when i print the returned value, it is always less(the array size is exactly 50 each time). Here is my code..

public function mainFunction(){
    $response = $fb->get('/me?fields=id,name,accounts', $useraccesstoken);    
    $userData = $response->getDecodedBody();
    $pages = $userData['accounts'];
    $pages = $this->getMorePages($pages);
}

public function getMorePages($pages){
    if(count($pages)>1 && isset($pages['paging']['next'])){
        $morePages = file_get_contents($pages['paging']['next']);
        $morePages = json_decode($morePages,true);
        foreach($morePages['data'] as $page){
            array_push($pages['data'],$page);
        }
        if(count($morePages)>1 && isset($morePages['paging']['next'])) {
            $pages['paging']['next']=$morePages['paging']['next'];
            $this->getMorePages($pages);
        }
        return $pages;
    }else{
        return $pages;
    }
}

What is the issue with my code..?


Solution

  • You are using a recursive function but not used the value return by the inner call...

    The fixed code is:

    public function getMorePages($pages){
        if(count($pages)>1 && isset($pages['paging']['next'])){
            $morePages = file_get_contents($pages['paging']['next']);
            $morePages = json_decode($morePages,true);
            foreach($morePages['data'] as $page){
                array_push($pages['data'],$page);
            }
            if(count($morePages)>1 && isset($morePages['paging']['next'])) {
                $pages['paging']['next']=$morePages['paging']['next'];
    
                // Add return values to the main array
                //$pages += $this->getMorePages($pages);
                // For more support use array_merge function
                $pages = array_merge( $this->getMorePages($pages), $pages )
            }
            return $pages;
        }else{
            return $pages;
        }
    }