Search code examples
phpvar-dump

Save var_dump output array objects into a variable


I am using the following code :

$key = 'xxx';
$secret = 'xxx';

$b = new Client ($key, $secret);
var_dump ($b->getMarketSummary ($market));

And the output of var_dump is like this :

array(1) {
 [0]=>
 object(stdClass)#3 (13) {
  ["MarketName"]=>string(7) "BTC-DAR"
  ["High"]=>float(5.7E-5)
  ["Bid"]=>float(5.276E-5)
  ["Ask"]=>float(5.43E-5)
  }
}

Now I want to save one of the above parameters in a separate variable so I can use it everywhere in my code and do other calculations. For example, I want to save "Ask" to $Ask and use it elsewhere. How can I do this?


Solution

  • First, assign the result of getMarketSummary to a variable. That way you'll be able to do other things with the result without calling that function again.

    $result = $b->getMarketSummary($market);
    

    Then, the result is just an object inside an array. Based on the method name, it looks like you would only expect one object in the array, so you shouldn't need to loop. Just use array and object notation to refer to the value you want.

    $ask = $result[0]->Ask;
    

    If I'm mistaken and it does return an array with more than one object, you can loop over it and do the same basic thing.

    foreach ($result as $item) {
        $ask = $item->Ask;
        echo $ask; // or whatever you're doing with it
    }