0

I'm trying to have this function return multiple results in array(?).

So basically instead of running lookup("354534", "name"); and lookup("354534", "date"); mutiple times for different results, how can I return both name & date from that function, then echo it out so I only have to use the function once?

    function lookup($data, $what)
 {
  $json = file_get_contents("http://site.com/".$data.".json");
  $output = json_decode($json, true);  
  echo $output['foo'][''.$what.''];
 }

Thanks!

user468797
  • 23
  • 1
  • 1
  • 3
  • Possible duplicate of [Multiple returns from function](http://stackoverflow.com/questions/3451906/multiple-returns-from-function) – miken32 May 29 '16 at 04:08

2 Answers2

0

Have the function return the whole JSON result:

function lookup($data)
{
    $json = file_get_contents("http://site.com/".$data.".json");
    $output = json_decode($json, true);  
    return $output["foo"];
}

then you can do

$result = lookup("354534");

echo $result["name"];
echo $result["date"];

This is really a good idea, because otherwise, you'll make the (slow) file_get_contents request multiple times, something you want to avoid.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
0

substitue echo in your function with return, and return the entire array:

function lookup($data){
  ...
  return $output;
  }

...

$results = lookup($someData);
echo $results['name'] . $results['date'];
fredley
  • 32,953
  • 42
  • 145
  • 236