1

Trying to return an array of items from api call, the var_dump spits out the array that I want, but the return is always null. What am I missing? Many thanks

function get_all_opened($mailgun, $domain, $list_address, $items, $page_advance = false, $next_url = false) 
{

    $end_point = "{$domain}/events";
    if($page_advance) {
        $end_point = "{$domain}/events/{$next_url}";
    }

    //API Call
    $stats = $mailgun->get($end_point, array(
        'event' => 'opened',
        'limit' => 25,
        'list' => $list_address
    ));

    $item_count = count($stats->http_response_body->items);

    if($item_count > 0) {
        $items[] = $stats->http_response_body->items;
    }
    if($item_count < 25) {
        var_dump($items); //Correct result set
        return $items; //Always NULL
    }

    if($item_count > 24) {
        $next_parts = explode ('/', $stats->http_response_body->paging->next);
        $next_url = end($next_parts);
        get_all_opened($mailgun, $domain, $list_address, $items, true, $next_url);
     }
}

$items = array();
get_all_opened($mailgun, $domain, $list_address, $items);
u_mulder
  • 54,101
  • 5
  • 48
  • 64
cee.e
  • 159
  • 1
  • 1
  • 9
  • 1
    Your `get_all_opened` function returns result which is not assigned to anything. – u_mulder Feb 08 '17 at 13:05
  • Sorry ignore that, even if the `get_all_opened` function is assigned `$opens = get_all_opened(..)` it still returns null – cee.e Feb 08 '17 at 13:07
  • The `$item_count < 25` is only called once (correctly), the var_dump at this point always has the correct result set, if I return it assign it etc, it is always null. – cee.e Feb 08 '17 at 13:10
  • 1
    Because `var_dump($items)` may happen deeper in a call stack. And items will be returned to "previous" `get_all_opened`. But nothing is returned in this "previous" `get_all_opened` – u_mulder Feb 08 '17 at 13:13
  • Ok thanks, that makes sense. I'm slightly lost as how to fix it though. – cee.e Feb 08 '17 at 13:49

1 Answers1

0

Fixed and working function below

function get_all_opened($mailgun, $domain, $list_address, $items, $page_advance = false, $next_url = false) {

  $end_point = "{$domain}/events";
  if($page_advance) {
    $end_point = "{$domain}/events/{$next_url}";
  }

  //API Call
  $stats = $mailgun->get($end_point, array(
      'event' => 'opened',
      'limit' => 25,
      'list' => $list_address
  ));


  $item_count = count($stats->http_response_body->items);

//add items to return array
  if($item_count > 0) {
    $items[] = $stats->http_response_body->items;
  }


  if($item_count > 24) {
    $next_parts = explode ('/', $stats->http_response_body->paging->next);
    $next_url = end($next_parts);
    return get_all_opened($mailgun, $domain, $list_address, $items, true, $next_url);
  } else {
    return $items;
  }

}
cee.e
  • 159
  • 1
  • 1
  • 9