The literal difference between the two loops
The for
loop in your snippet iterates over the array $yahoo_json_decoded->ResultSet->Result
, while the foreach
loop iterates over the object $yahoo_json_decoded->ResultSet
.
In other words, in the for
loop you're iterating over the array elements as you expect, whereas in the foreach
loop you are in fact iterating over the object properties.
A demonstration of the difference
For example, given this object:
$json = json_encode(array('result'=>array('apple','orange','lemon')));
$obj = json_decode($json);
consider the difference between this loop:
for ($i=0; $i < count($obj->result); $i++) :
echo $i.' - '.$obj->result[$i].' ';
endfor;
and this loop:
foreach ($obj as $key=>$val) :
echo $key.' - ';
var_dump($val);
endforeach;
The output of the first loop will be:
0 - apple 1 - orange 2 - lemon
While the output of the second will be:
result - array(3) { [0]=> string(5) "apple" [1]=> string(6) "orange" [2]=> string(5) "lemon" }