Cristi ┼×erban Cristi ┼×erban - 3 months ago 7
PHP Question

Iteration through an array

I need some help and explanation because I did not quite understand how to iterate through an array and make an arithmetic mean of some data. I am just starting on my road with php so some explanation would be nice.
I have an array stored in a variable

$data
. It looks like this:

["data"]=>
array(22) {
[0]=>
object(stdClass)#234 (7) {
["Date"]=>
string(10) "2016-08-31"
["Open"]=>
string(9) "767.01001"
["High"]=>
string(10) "769.090027"
["Low"]=>
string(10) "765.380005"
["Close"]=>
string(10) "767.049988"
["Volume"]=>
string(7) "1247400"
["AdjClose"]=>
string(10) "767.049988"
}
[1]=>
object(stdClass)#240 (7) {
["Date"]=>
string(10) "2016-08-30"
["Open"]=>
string(10) "769.330017"
["High"]=>
string(10) "774.466003"
["Low"]=>
string(10) "766.840027"
["Close"]=>
string(10) "769.090027"
["Volume"]=>
string(7) "1127100"
["AdjClose"]=>
string(10) "769.090027"
}


It has around 22 entries and I want to iterate through every ["AdjClose"] and make a mean this numbers, so from what I understand I should write something like:
if(@$data->data->AdjClose)
but this is where my problems begin...can someone explain to me please how to iterate through AdjClose and store the mean of those numbers in a variable? I am sorry for this noobish question.

Answer

Here's an example of an iterative solution, since you were asking about how that would work:

// initialize sum and total
$sum = 0;
$total = 0;

foreach ($data->data as $obj) {
    if (isset($obj->AdjClose)) {   // verify that the current object has an AdjClose
        $sum += $obj->AdjClose;    // add it to the sum
        $total++;                  // increment the count
    }
}
echo $sum / $total;                // display the average

I added the if (isset($obj->AdjClose) check because you asked about if(@$data->data->AdjClose). I thought that implied that AdjClose might not be present in some of the objects. If that is the case, I wanted to show how to check for it rather than using the error suppression operator (@).


If you have PHP 7, you can also do this using array_column (but only if AdjClose is defined on all of the objects).

$average = array_sum(array_column($data->data, 'AdjClose')) / count($data->data)
Comments