简体   繁体   中英

Calculate average percentage difference in a php array

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 3
    [6] => 1
)

I was wondering how one would go about working out the average percentage difference between the current value in an array and the next value. If the next value were a larger one, it would perform like so. (ie keys [0]-[1] 1/2 * 100 = 50). If it were a smaller value it would perform like so. (ie keys [4]-[5] = 3/5 * 100 = -60).

The following will represent what I am aiming to do with these percentage calculations.

1/2 * 100

2/3 * 100

3/4 * 100

4/5 * 100

3/5 * 100 (negative)

1/3 * 100 (negative)


Total : total/count

This will iterate through the list and then work out the average from the count. I have looked into splitting arrays but don't see how else I could do this.

$count = count($num); 
foreach ($num as $value) {
    array_chunk($num, 1);
    if($value<$value){
    $total1 = $total1 + ($value/$value)*100;
    }
    if($value>$value){
    $total2 = $total2 + ($value/$value)*100;
    }
}
$average = (($total1-$total2)/$count);
print($average);

I understand the above code is incorrect, but I hope it reveals where I am getting at with this.

Any help would be greatly appreciated.

You don't want to use foreach as you'll always be needing two array elements. Note that this snippet does not protect you from 0 values. These will make your script fail.

$num   = array(1, 2, 3, 4, 5, 3, 1); 
$total = 0;
// The number of percent changes is one less than
// the size of your array.
$count = count($num) - 1;
// Array indexes start at 0
for ($i = 0; $i < $count; $i++) {
    // The current number is $num[$i], and the
    // next is $num[$i + 1]; knowing that it's
    // pretty easy to compare them.
    if ($num[$i] < $num[$i + 1]) {
        $total += (100 * $num[$i] / $num[$i + 1]);
    }   
    else {
        $total += (-100 * $num[$i + 1] / $num[$i]);
    };  
};
echo ($total / $count);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM